blob: d8fd16c5e6f4520f86ed4e443d11b078c65dd075 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -070019#include <android-base/properties.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080020#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070021#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070022#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080023#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100024#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026
Garfield Tan1c7bc862020-01-28 13:24:04 -080027#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070028#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080029#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080030#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080031
Garfield Tan1c7bc862020-01-28 13:24:04 -080032using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050033using android::gui::FocusRequest;
34using android::gui::TouchOcclusionMode;
35using android::gui::WindowInfo;
36using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080037using android::os::InputEventInjectionResult;
38using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010039using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080040
Garfield Tane84e6f92019-08-29 17:28:41 -070041namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080042
43// An arbitrary time value.
44static const nsecs_t ARBITRARY_TIME = 1234;
45
46// An arbitrary device id.
47static const int32_t DEVICE_ID = 1;
48
Jeff Brownf086ddb2014-02-11 14:28:48 -080049// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000050static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
51static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053// An arbitrary injector pid / uid pair that has permission to inject events.
54static const int32_t INJECTOR_PID = 999;
55static const int32_t INJECTOR_UID = 1001;
56
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000057// An arbitrary pid of the gesture monitor window
58static constexpr int32_t MONITOR_PID = 2001;
59
chaviwd1c23182019-12-20 18:44:56 -080060struct PointF {
61 float x;
62 float y;
63};
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Gang Wang342c9272020-01-13 13:15:04 -050065/**
66 * Return a DOWN key event with KEYCODE_A.
67 */
68static KeyEvent getTestKeyEvent() {
69 KeyEvent event;
70
Garfield Tanfbe732e2020-01-24 11:26:14 -080071 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
72 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
73 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050074 return event;
75}
76
Siarhei Vishniakouca205502021-07-16 21:31:58 +000077static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
78 ASSERT_EQ(expectedAction, receivedAction)
79 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
80 << MotionEvent::actionToString(receivedAction);
81}
82
Michael Wrightd02c5b62014-02-10 15:10:22 -080083// --- FakeInputDispatcherPolicy ---
84
85class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
86 InputDispatcherConfiguration mConfig;
87
88protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100089 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080090
91public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100092 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080093
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080094 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070095 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
96 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
97 EXPECT_EQ(event.getDisplayId(), args.displayId);
98
99 const auto& keyEvent = static_cast<const KeyEvent&>(event);
100 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
101 EXPECT_EQ(keyEvent.getAction(), args.action);
102 });
Jackal Guof9696682018-10-05 12:23:23 +0800103 }
104
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700105 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
106 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
107 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
108 EXPECT_EQ(event.getDisplayId(), args.displayId);
109
110 const auto& motionEvent = static_cast<const MotionEvent&>(event);
111 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
112 EXPECT_EQ(motionEvent.getAction(), args.action);
113 EXPECT_EQ(motionEvent.getX(0), point.x);
114 EXPECT_EQ(motionEvent.getY(0), point.y);
115 EXPECT_EQ(motionEvent.getRawX(0), point.x);
116 EXPECT_EQ(motionEvent.getRawY(0), point.y);
117 });
Jackal Guof9696682018-10-05 12:23:23 +0800118 }
119
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700120 void assertFilterInputEventWasNotCalled() {
121 std::scoped_lock lock(mLock);
122 ASSERT_EQ(nullptr, mFilteredEvent);
123 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800125 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700126 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800127 ASSERT_TRUE(mConfigurationChangedTime)
128 << "Timed out waiting for configuration changed call";
129 ASSERT_EQ(*mConfigurationChangedTime, when);
130 mConfigurationChangedTime = std::nullopt;
131 }
132
133 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700134 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800135 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800136 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
138 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
139 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
140 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
141 mLastNotifySwitch = std::nullopt;
142 }
143
chaviwfd6d3512019-03-25 13:23:49 -0700144 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700145 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800146 ASSERT_EQ(touchedToken, mOnPointerDownToken);
147 mOnPointerDownToken.clear();
148 }
149
150 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700151 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800152 ASSERT_TRUE(mOnPointerDownToken == nullptr)
153 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700154 }
155
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700156 // This function must be called soon after the expected ANR timer starts,
157 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500158 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700159 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500160 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
161 std::shared_ptr<InputApplicationHandle> application;
162 { // acquire lock
163 std::unique_lock lock(mLock);
164 android::base::ScopedLockAssertion assumeLocked(mLock);
165 ASSERT_NO_FATAL_FAILURE(
166 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
167 } // release lock
168 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700169 }
170
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000171 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
172 const sp<IBinder>& expectedConnectionToken) {
173 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500174 ASSERT_EQ(expectedConnectionToken, connectionToken);
175 }
176
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000177 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
178 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500179 ASSERT_EQ(expectedConnectionToken, connectionToken);
180 }
181
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000182 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
183 int32_t pid = getUnresponsiveMonitorPid(timeout);
184 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500185 }
186
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000187 void assertNotifyMonitorResponsiveWasCalled() {
188 int32_t pid = getResponsiveMonitorPid();
189 ASSERT_EQ(MONITOR_PID, pid);
190 }
191
192 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500193 std::unique_lock lock(mLock);
194 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000195 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
196 }
197
198 sp<IBinder> getResponsiveWindowToken() {
199 std::unique_lock lock(mLock);
200 android::base::ScopedLockAssertion assumeLocked(mLock);
201 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
202 }
203
204 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
205 std::unique_lock lock(mLock);
206 android::base::ScopedLockAssertion assumeLocked(mLock);
207 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
208 }
209
210 int32_t getResponsiveMonitorPid() {
211 std::unique_lock lock(mLock);
212 android::base::ScopedLockAssertion assumeLocked(mLock);
213 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500214 }
215
216 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
217 // for a specific container to become non-empty. When the container is non-empty, return the
218 // first entry from the container and erase it.
219 template <class T>
220 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
221 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
222 const std::chrono::time_point start = std::chrono::steady_clock::now();
223 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700224
225 // If there is an ANR, Dispatcher won't be idle because there are still events
226 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
227 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500228 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
229 // to provide it some time to act. 100ms seems reasonable.
230 mNotifyAnr.wait_for(lock, timeToWait,
231 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700232 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500233 if (storage.empty()) {
234 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700236 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700237 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
238 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700239 if (std::chrono::abs(timeout - waited) > 100ms) {
240 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
241 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
242 << "ms, but waited "
243 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
244 << "ms instead";
245 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500246 T token = storage.front();
247 storage.pop();
248 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700249 }
250
251 void assertNotifyAnrWasNotCalled() {
252 std::scoped_lock lock(mLock);
253 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000254 ASSERT_TRUE(mAnrWindowTokens.empty());
255 ASSERT_TRUE(mAnrMonitorPids.empty());
256 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500257 << "ANR was not called, but please also consume the 'connection is responsive' "
258 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000259 ASSERT_TRUE(mResponsiveMonitorPids.empty())
260 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
261 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700262 }
263
Garfield Tan1c7bc862020-01-28 13:24:04 -0800264 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
265 mConfig.keyRepeatTimeout = timeout;
266 mConfig.keyRepeatDelay = delay;
267 }
268
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000269 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800270 std::unique_lock lock(mLock);
271 base::ScopedLockAssertion assumeLocked(mLock);
272
273 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
274 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000275 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800276 enabled;
277 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
279 << ") to be called.";
280 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000282 auto request = *mPointerCaptureRequest;
283 mPointerCaptureRequest.reset();
284 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800285 }
286
287 void assertSetPointerCaptureNotCalled() {
288 std::unique_lock lock(mLock);
289 base::ScopedLockAssertion assumeLocked(mLock);
290
291 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000292 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800293 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000294 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800295 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000296 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800297 }
298
arthurhungf452d0b2021-01-06 00:19:52 +0800299 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
300 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800301 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800302 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800303 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800304 }
305
Michael Wrightd02c5b62014-02-10 15:10:22 -0800306private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700307 std::mutex mLock;
308 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
309 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
310 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
311 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800312
Prabir Pradhan99987712020-11-10 18:43:05 -0800313 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000314
315 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800316
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700317 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700318 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000319 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
320 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
321 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
322 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700323 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700324
arthurhungf452d0b2021-01-06 00:19:52 +0800325 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800326 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800327
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600328 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700329 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800330 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331 }
332
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000333 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700334 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000335 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700336 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500337 }
338
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000339 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500340 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000341 mAnrMonitorPids.push(pid);
342 mNotifyAnr.notify_all();
343 }
344
345 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
346 std::scoped_lock lock(mLock);
347 mResponsiveWindowTokens.push(connectionToken);
348 mNotifyAnr.notify_all();
349 }
350
351 void notifyMonitorResponsive(int32_t pid) override {
352 std::scoped_lock lock(mLock);
353 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500354 mNotifyAnr.notify_all();
355 }
356
357 void notifyNoFocusedWindowAnr(
358 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
359 std::scoped_lock lock(mLock);
360 mAnrApplications.push(applicationHandle);
361 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362 }
363
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600364 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600366 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700367
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600368 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700369 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
370 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
371 const std::vector<float>& values) override {}
372
373 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
374 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000375
Chris Yefb552902021-02-03 17:18:37 -0800376 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
377
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600378 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379 *outConfig = mConfig;
380 }
381
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600382 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700383 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800384 switch (inputEvent->getType()) {
385 case AINPUT_EVENT_TYPE_KEY: {
386 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800387 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800388 break;
389 }
390
391 case AINPUT_EVENT_TYPE_MOTION: {
392 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800393 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800394 break;
395 }
396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397 return true;
398 }
399
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600400 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600402 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600404 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 return 0;
406 }
407
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600408 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 return false;
410 }
411
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600412 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
413 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700414 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800415 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
416 * essentially a passthrough for notifySwitch.
417 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800418 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 }
420
Sean Stoutb4e0a592021-02-23 07:34:53 -0800421 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800423 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
424 return pid == INJECTOR_PID && uid == INJECTOR_UID;
425 }
Jackal Guof9696682018-10-05 12:23:23 +0800426
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600427 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700428 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700429 mOnPointerDownToken = newToken;
430 }
431
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000432 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800433 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000434 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800435 mPointerCaptureChangedCondition.notify_all();
436 }
437
arthurhungf452d0b2021-01-06 00:19:52 +0800438 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
439 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800440 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800441 mDropTargetWindowToken = token;
442 }
443
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700444 void assertFilterInputEventWasCalledInternal(
445 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700446 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800447 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700448 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800449 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800450 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451};
452
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453// --- InputDispatcherTest ---
454
455class InputDispatcherTest : public testing::Test {
456protected:
457 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700458 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000460 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800461 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700462 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800463 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000464 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700465 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 }
467
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000468 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700469 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700471 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700473
474 /**
475 * Used for debugging when writing the test
476 */
477 void dumpDispatcherState() {
478 std::string dump;
479 mDispatcher->dump(dump);
480 std::stringstream ss(dump);
481 std::string to;
482
483 while (std::getline(ss, to, '\n')) {
484 ALOGE("%s", to.c_str());
485 }
486 }
Vishnu Nair958da932020-08-21 17:12:37 -0700487
chaviw3277faf2021-05-19 16:45:23 -0500488 void setFocusedWindow(const sp<WindowInfoHandle>& window,
489 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700490 FocusRequest request;
491 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000492 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700493 if (focusedWindow) {
494 request.focusedToken = focusedWindow->getToken();
495 }
496 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
497 request.displayId = window->getInfo()->displayId;
498 mDispatcher->setFocusedWindow(request);
499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500};
501
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
503 KeyEvent event;
504
505 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800506 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
507 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600508 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
509 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800510 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700511 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800512 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800513 << "Should reject key events with undefined action.";
514
515 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800516 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
517 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600518 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800519 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700520 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800521 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 << "Should reject key events with ACTION_MULTIPLE.";
523}
524
525TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
526 MotionEvent event;
527 PointerProperties pointerProperties[MAX_POINTERS + 1];
528 PointerCoords pointerCoords[MAX_POINTERS + 1];
529 for (int i = 0; i <= MAX_POINTERS; i++) {
530 pointerProperties[i].clear();
531 pointerProperties[i].id = i;
532 pointerCoords[i].clear();
533 }
534
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800535 // Some constants commonly used below
536 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
537 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
538 constexpr int32_t metaState = AMETA_NONE;
539 constexpr MotionClassification classification = MotionClassification::NONE;
540
chaviw9eaa22c2020-07-01 16:21:27 -0700541 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800543 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700544 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
545 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700546 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
547 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700548 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800549 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700550 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 << "Should reject motion events with undefined action.";
553
554 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800555 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700556 AMOTION_EVENT_ACTION_POINTER_DOWN |
557 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700558 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
559 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700560 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500561 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800562 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700563 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800564 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 << "Should reject motion events with pointer down index too large.";
566
Garfield Tanfbe732e2020-01-24 11:26:14 -0800567 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700568 AMOTION_EVENT_ACTION_POINTER_DOWN |
569 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700570 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
571 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700572 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500573 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800574 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700575 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800577 << "Should reject motion events with pointer down index too small.";
578
579 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800580 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700581 AMOTION_EVENT_ACTION_POINTER_UP |
582 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700583 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
584 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700585 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500586 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800587 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700588 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800589 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 << "Should reject motion events with pointer up index too large.";
591
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700593 AMOTION_EVENT_ACTION_POINTER_UP |
594 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700595 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
596 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700597 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500598 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700600 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800601 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject motion events with pointer up index too small.";
603
604 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
606 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700607 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700608 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
609 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700610 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700612 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800613 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 << "Should reject motion events with 0 pointers.";
615
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
617 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700618 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700619 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
620 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with more than MAX_POINTERS pointers.";
626
627 // Rejects motion events with invalid pointer ids.
628 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
630 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700631 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700632 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
633 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700634 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700636 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800637 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 << "Should reject motion events with pointer ids less than 0.";
639
640 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800641 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
642 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700643 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700644 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
645 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700646 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700648 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800649 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
651
652 // Rejects motion events with duplicate pointer ids.
653 pointerProperties[0].id = 1;
654 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800655 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
656 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700657 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700658 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
659 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700660 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800661 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700662 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800663 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 << "Should reject motion events with duplicate pointer ids.";
665}
666
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800667/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
668
669TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
670 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800671 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800672 mDispatcher->notifyConfigurationChanged(&args);
673 ASSERT_TRUE(mDispatcher->waitForIdle());
674
675 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
676}
677
678TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800679 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
680 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800681 mDispatcher->notifySwitch(&args);
682
683 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
684 args.policyFlags |= POLICY_FLAG_TRUSTED;
685 mFakePolicy->assertNotifySwitchWasCalled(args);
686}
687
Arthur Hungb92218b2018-08-14 12:00:21 +0800688// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700689static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700690// Default input dispatching timeout if there is no focused application or paused window
691// from which to determine an appropriate dispatching timeout.
692static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
693 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
694 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800695
696class FakeApplicationHandle : public InputApplicationHandle {
697public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700698 FakeApplicationHandle() {
699 mInfo.name = "Fake Application";
700 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500701 mInfo.dispatchingTimeoutMillis =
702 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700703 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800704 virtual ~FakeApplicationHandle() {}
705
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000706 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700707
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500708 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
709 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700710 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800711};
712
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800713class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800714public:
Garfield Tan15601662020-09-22 15:32:38 -0700715 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800716 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700717 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800718 }
719
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800720 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700721 InputEvent* event;
722 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
723 if (!consumeSeq) {
724 return nullptr;
725 }
726 finishEvent(*consumeSeq);
727 return event;
728 }
729
730 /**
731 * Receive an event without acknowledging it.
732 * Return the sequence number that could later be used to send finished signal.
733 */
734 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800735 uint32_t consumeSeq;
736 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800737
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800738 std::chrono::time_point start = std::chrono::steady_clock::now();
739 status_t status = WOULD_BLOCK;
740 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800741 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800742 &event);
743 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
744 if (elapsed > 100ms) {
745 break;
746 }
747 }
748
749 if (status == WOULD_BLOCK) {
750 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800752 }
753
754 if (status != OK) {
755 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700756 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800757 }
758 if (event == nullptr) {
759 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700760 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800761 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700762 if (outEvent != nullptr) {
763 *outEvent = event;
764 }
765 return consumeSeq;
766 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700768 /**
769 * To be used together with "receiveEvent" to complete the consumption of an event.
770 */
771 void finishEvent(uint32_t consumeSeq) {
772 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
773 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800774 }
775
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000776 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
777 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
778 ASSERT_EQ(OK, status);
779 }
780
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000781 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
782 std::optional<int32_t> expectedDisplayId,
783 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800784 InputEvent* event = consume();
785
786 ASSERT_NE(nullptr, event) << mName.c_str()
787 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800788 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700789 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800790 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800791
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000792 if (expectedDisplayId.has_value()) {
793 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
794 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800795
Tiger Huang8664f8c2018-10-11 19:14:35 +0800796 switch (expectedEventType) {
797 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800798 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
799 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000800 if (expectedFlags.has_value()) {
801 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
802 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800803 break;
804 }
805 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800806 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000807 assertMotionAction(expectedAction, motionEvent.getAction());
808
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000809 if (expectedFlags.has_value()) {
810 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
811 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800812 break;
813 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100814 case AINPUT_EVENT_TYPE_FOCUS: {
815 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
816 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800817 case AINPUT_EVENT_TYPE_CAPTURE: {
818 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
819 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000820 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
821 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
822 }
arthurhungb89ccb02020-12-30 16:19:01 +0800823 case AINPUT_EVENT_TYPE_DRAG: {
824 FAIL() << "Use 'consumeDragEvent' for DRAG events";
825 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826 default: {
827 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
828 }
829 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800830 }
831
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100832 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
833 InputEvent* event = consume();
834 ASSERT_NE(nullptr, event) << mName.c_str()
835 << ": consumer should have returned non-NULL event.";
836 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
837 << "Got " << inputEventTypeToString(event->getType())
838 << " event instead of FOCUS event";
839
840 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
841 << mName.c_str() << ": event displayId should always be NONE.";
842
843 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
844 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
845 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
846 }
847
Prabir Pradhan99987712020-11-10 18:43:05 -0800848 void consumeCaptureEvent(bool hasCapture) {
849 const InputEvent* event = consume();
850 ASSERT_NE(nullptr, event) << mName.c_str()
851 << ": consumer should have returned non-NULL event.";
852 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
853 << "Got " << inputEventTypeToString(event->getType())
854 << " event instead of CAPTURE event";
855
856 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
857 << mName.c_str() << ": event displayId should always be NONE.";
858
859 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
860 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
861 }
862
arthurhungb89ccb02020-12-30 16:19:01 +0800863 void consumeDragEvent(bool isExiting, float x, float y) {
864 const InputEvent* event = consume();
865 ASSERT_NE(nullptr, event) << mName.c_str()
866 << ": consumer should have returned non-NULL event.";
867 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
868 << "Got " << inputEventTypeToString(event->getType())
869 << " event instead of DRAG event";
870
871 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
872 << mName.c_str() << ": event displayId should always be NONE.";
873
874 const auto& dragEvent = static_cast<const DragEvent&>(*event);
875 EXPECT_EQ(isExiting, dragEvent.isExiting());
876 EXPECT_EQ(x, dragEvent.getX());
877 EXPECT_EQ(y, dragEvent.getY());
878 }
879
Antonio Kantekf16f2832021-09-28 04:39:20 +0000880 void consumeTouchModeEvent(bool inTouchMode) {
881 const InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of TOUCH_MODE event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
891 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
892 }
893
chaviwd1c23182019-12-20 18:44:56 -0800894 void assertNoEvents() {
895 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700896 if (event == nullptr) {
897 return;
898 }
899 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
900 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
901 ADD_FAILURE() << "Received key event "
902 << KeyEvent::actionToString(keyEvent.getAction());
903 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
904 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
905 ADD_FAILURE() << "Received motion event "
906 << MotionEvent::actionToString(motionEvent.getAction());
907 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
908 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
909 ADD_FAILURE() << "Received focus event, hasFocus = "
910 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800911 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
912 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
913 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
914 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000915 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
916 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
917 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
918 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700919 }
920 FAIL() << mName.c_str()
921 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800922 }
923
924 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
925
926protected:
927 std::unique_ptr<InputConsumer> mConsumer;
928 PreallocatedInputEventFactory mEventFactory;
929
930 std::string mName;
931};
932
chaviw3277faf2021-05-19 16:45:23 -0500933class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800934public:
935 static const int32_t WIDTH = 600;
936 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800937
Chris Yea209fde2020-07-22 13:54:51 -0700938 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700939 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500940 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800941 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500942 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700943 base::Result<std::unique_ptr<InputChannel>> channel =
944 dispatcher->createInputChannel(name);
945 token = (*channel)->getConnectionToken();
946 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800947 }
948
949 inputApplicationHandle->updateInfo();
950 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
951
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500952 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700953 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800954 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500955 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500956 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000957 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800958 mInfo.frameLeft = 0;
959 mInfo.frameTop = 0;
960 mInfo.frameRight = WIDTH;
961 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700962 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800963 mInfo.globalScaleFactor = 1.0;
964 mInfo.touchableRegion.clear();
965 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
966 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700967 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800968 mInfo.hasWallpaper = false;
969 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800970 mInfo.ownerPid = INJECTOR_PID;
971 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800972 mInfo.displayId = displayId;
973 }
974
Arthur Hungabbb9d82021-09-01 14:52:30 +0000975 sp<FakeWindowHandle> clone(
976 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700977 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +0000978 sp<FakeWindowHandle> handle =
979 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
980 displayId, mInfo.token);
981 return handle;
982 }
983
Vishnu Nair47074b82020-08-14 11:54:47 -0700984 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800985
Vishnu Nair958da932020-08-21 17:12:37 -0700986 void setVisible(bool visible) { mInfo.visible = visible; }
987
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700988 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500989 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700990 }
991
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700992 void setPaused(bool paused) { mInfo.paused = paused; }
993
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000994 void setAlpha(float alpha) { mInfo.alpha = alpha; }
995
chaviw3277faf2021-05-19 16:45:23 -0500996 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000997
Bernardo Rufino7393d172021-02-26 13:56:11 +0000998 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
999
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001000 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001001 mInfo.frameLeft = frame.left;
1002 mInfo.frameTop = frame.top;
1003 mInfo.frameRight = frame.right;
1004 mInfo.frameBottom = frame.bottom;
1005 mInfo.touchableRegion.clear();
1006 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001007
1008 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1009 ui::Transform translate;
1010 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1011 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001012 }
1013
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001014 void setType(WindowInfo::Type type) { mInfo.type = type; }
1015
1016 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1017
chaviw3277faf2021-05-19 16:45:23 -05001018 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001019
chaviw3277faf2021-05-19 16:45:23 -05001020 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001021
chaviw3277faf2021-05-19 16:45:23 -05001022 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001023
chaviw9eaa22c2020-07-01 16:21:27 -07001024 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1025 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1026 }
1027
1028 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001029
yunho.shinf4a80b82020-11-16 21:13:57 +09001030 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1031
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001032 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1033 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1034 expectedFlags);
1035 }
1036
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001037 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1038 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1039 }
1040
Svet Ganov5d3bc372020-01-26 23:11:07 -08001041 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001042 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001043 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1044 expectedFlags);
1045 }
1046
1047 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001048 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001049 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1050 expectedFlags);
1051 }
1052
1053 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001054 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001055 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1056 }
1057
1058 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1059 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001060 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1061 expectedFlags);
1062 }
1063
Svet Ganov5d3bc372020-01-26 23:11:07 -08001064 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001065 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1066 int32_t expectedFlags = 0) {
1067 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1068 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001069 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1070 }
1071
1072 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001073 int32_t expectedFlags = 0) {
1074 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1075 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001076 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1077 }
1078
1079 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001080 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001081 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1082 expectedFlags);
1083 }
1084
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001085 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1086 int32_t expectedFlags = 0) {
1087 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1088 expectedFlags);
1089 }
1090
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001091 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1092 ASSERT_NE(mInputReceiver, nullptr)
1093 << "Cannot consume events from a window with no receiver";
1094 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1095 }
1096
Prabir Pradhan99987712020-11-10 18:43:05 -08001097 void consumeCaptureEvent(bool hasCapture) {
1098 ASSERT_NE(mInputReceiver, nullptr)
1099 << "Cannot consume events from a window with no receiver";
1100 mInputReceiver->consumeCaptureEvent(hasCapture);
1101 }
1102
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001103 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1104 std::optional<int32_t> expectedDisplayId,
1105 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001106 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1107 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1108 expectedFlags);
1109 }
1110
arthurhungb89ccb02020-12-30 16:19:01 +08001111 void consumeDragEvent(bool isExiting, float x, float y) {
1112 mInputReceiver->consumeDragEvent(isExiting, x, y);
1113 }
1114
Antonio Kantekf16f2832021-09-28 04:39:20 +00001115 void consumeTouchModeEvent(bool inTouchMode) {
1116 ASSERT_NE(mInputReceiver, nullptr)
1117 << "Cannot consume events from a window with no receiver";
1118 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1119 }
1120
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001121 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001122 if (mInputReceiver == nullptr) {
1123 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1124 return std::nullopt;
1125 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001126 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001127 }
1128
1129 void finishEvent(uint32_t sequenceNum) {
1130 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1131 mInputReceiver->finishEvent(sequenceNum);
1132 }
1133
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001134 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1135 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1136 mInputReceiver->sendTimeline(inputEventId, timeline);
1137 }
1138
chaviwaf87b3e2019-10-01 16:59:28 -07001139 InputEvent* consume() {
1140 if (mInputReceiver == nullptr) {
1141 return nullptr;
1142 }
1143 return mInputReceiver->consume();
1144 }
1145
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001146 MotionEvent* consumeMotion() {
1147 InputEvent* event = consume();
1148 if (event == nullptr) {
1149 ADD_FAILURE() << "Consume failed : no event";
1150 return nullptr;
1151 }
1152 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1153 ADD_FAILURE() << "Instead of motion event, got "
1154 << inputEventTypeToString(event->getType());
1155 return nullptr;
1156 }
1157 return static_cast<MotionEvent*>(event);
1158 }
1159
Arthur Hungb92218b2018-08-14 12:00:21 +08001160 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001161 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001162 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001163 return; // Can't receive events if the window does not have input channel
1164 }
1165 ASSERT_NE(nullptr, mInputReceiver)
1166 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001167 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001168 }
1169
chaviwaf87b3e2019-10-01 16:59:28 -07001170 sp<IBinder> getToken() { return mInfo.token; }
1171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 const std::string& getName() { return mName; }
1173
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001174 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1175 mInfo.ownerPid = ownerPid;
1176 mInfo.ownerUid = ownerUid;
1177 }
1178
chaviwd1c23182019-12-20 18:44:56 -08001179private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001180 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001181 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001182 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001183};
1184
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001185std::atomic<int32_t> FakeWindowHandle::sId{1};
1186
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001187static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001188 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001189 int32_t displayId = ADISPLAY_ID_NONE,
1190 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001191 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1192 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001193 KeyEvent event;
1194 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1195
1196 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001197 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001198 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1199 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001200
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001201 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1202 if (!allowKeyRepeat) {
1203 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1204 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001205 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001206 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001207 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001208}
1209
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001210static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001211 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001212 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1213}
1214
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001215// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1216// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1217// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001218static InputEventInjectionResult injectKeyDownNoRepeat(
1219 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001220 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1221 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1222 /* allowKeyRepeat */ false);
1223}
1224
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001225static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001226 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001227 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1228}
1229
Garfield Tandf26e862020-07-01 20:18:19 -07001230class PointerBuilder {
1231public:
1232 PointerBuilder(int32_t id, int32_t toolType) {
1233 mProperties.clear();
1234 mProperties.id = id;
1235 mProperties.toolType = toolType;
1236 mCoords.clear();
1237 }
1238
1239 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1240
1241 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1242
1243 PointerBuilder& axis(int32_t axis, float value) {
1244 mCoords.setAxisValue(axis, value);
1245 return *this;
1246 }
1247
1248 PointerProperties buildProperties() const { return mProperties; }
1249
1250 PointerCoords buildCoords() const { return mCoords; }
1251
1252private:
1253 PointerProperties mProperties;
1254 PointerCoords mCoords;
1255};
1256
1257class MotionEventBuilder {
1258public:
1259 MotionEventBuilder(int32_t action, int32_t source) {
1260 mAction = action;
1261 mSource = source;
1262 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1263 }
1264
1265 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1266 mEventTime = eventTime;
1267 return *this;
1268 }
1269
1270 MotionEventBuilder& displayId(int32_t displayId) {
1271 mDisplayId = displayId;
1272 return *this;
1273 }
1274
1275 MotionEventBuilder& actionButton(int32_t actionButton) {
1276 mActionButton = actionButton;
1277 return *this;
1278 }
1279
arthurhung6d4bed92021-03-17 11:59:33 +08001280 MotionEventBuilder& buttonState(int32_t buttonState) {
1281 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001282 return *this;
1283 }
1284
1285 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1286 mRawXCursorPosition = rawXCursorPosition;
1287 return *this;
1288 }
1289
1290 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1291 mRawYCursorPosition = rawYCursorPosition;
1292 return *this;
1293 }
1294
1295 MotionEventBuilder& pointer(PointerBuilder pointer) {
1296 mPointers.push_back(pointer);
1297 return *this;
1298 }
1299
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001300 MotionEventBuilder& addFlag(uint32_t flags) {
1301 mFlags |= flags;
1302 return *this;
1303 }
1304
Garfield Tandf26e862020-07-01 20:18:19 -07001305 MotionEvent build() {
1306 std::vector<PointerProperties> pointerProperties;
1307 std::vector<PointerCoords> pointerCoords;
1308 for (const PointerBuilder& pointer : mPointers) {
1309 pointerProperties.push_back(pointer.buildProperties());
1310 pointerCoords.push_back(pointer.buildCoords());
1311 }
1312
1313 // Set mouse cursor position for the most common cases to avoid boilerplate.
1314 if (mSource == AINPUT_SOURCE_MOUSE &&
1315 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1316 mPointers.size() == 1) {
1317 mRawXCursorPosition = pointerCoords[0].getX();
1318 mRawYCursorPosition = pointerCoords[0].getY();
1319 }
1320
1321 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001322 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001323 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001324 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001325 mButtonState, MotionClassification::NONE, identityTransform,
1326 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001327 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1328 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001329
1330 return event;
1331 }
1332
1333private:
1334 int32_t mAction;
1335 int32_t mSource;
1336 nsecs_t mEventTime;
1337 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1338 int32_t mActionButton{0};
1339 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001340 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001341 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1342 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1343
1344 std::vector<PointerBuilder> mPointers;
1345};
1346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001347static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001348 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001349 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001350 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001351 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1352 injectionTimeout,
1353 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1354}
1355
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001356static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001357 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1358 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001359 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001360 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1361 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001362 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001363 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001364 MotionEvent event = MotionEventBuilder(action, source)
1365 .displayId(displayId)
1366 .eventTime(eventTime)
1367 .rawXCursorPosition(cursorPosition.x)
1368 .rawYCursorPosition(cursorPosition.y)
1369 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1370 .x(position.x)
1371 .y(position.y))
1372 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001373
1374 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001375 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001376}
1377
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001378static InputEventInjectionResult injectMotionDown(
1379 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1380 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001381 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001382}
1383
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001384static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001385 int32_t source, int32_t displayId,
1386 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001387 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001388}
1389
Jackal Guof9696682018-10-05 12:23:23 +08001390static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1391 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1392 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001393 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1394 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1395 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001396
1397 return args;
1398}
1399
chaviwd1c23182019-12-20 18:44:56 -08001400static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1401 const std::vector<PointF>& points) {
1402 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001403 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1404 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1405 }
1406
chaviwd1c23182019-12-20 18:44:56 -08001407 PointerProperties pointerProperties[pointerCount];
1408 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001409
chaviwd1c23182019-12-20 18:44:56 -08001410 for (size_t i = 0; i < pointerCount; i++) {
1411 pointerProperties[i].clear();
1412 pointerProperties[i].id = i;
1413 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001414
chaviwd1c23182019-12-20 18:44:56 -08001415 pointerCoords[i].clear();
1416 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1417 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1418 }
Jackal Guof9696682018-10-05 12:23:23 +08001419
1420 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1421 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001422 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001423 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1424 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001425 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1426 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001427 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1428 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001429
1430 return args;
1431}
1432
chaviwd1c23182019-12-20 18:44:56 -08001433static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1434 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1435}
1436
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001437static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1438 const PointerCaptureRequest& request) {
1439 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001440}
1441
Arthur Hungb92218b2018-08-14 12:00:21 +08001442TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001443 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001444 sp<FakeWindowHandle> window =
1445 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001446
Arthur Hung72d8dc32020-03-28 00:48:39 +00001447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001451
1452 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001453 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001454}
1455
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001456TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1457 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1458 sp<FakeWindowHandle> window =
1459 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1460
1461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1462 // Inject a MotionEvent to an unknown display.
1463 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1464 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1465 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1466
1467 // Window should receive motion event.
1468 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1469}
1470
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001471/**
1472 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1473 * To ensure that window receives only events that were directly inside of it, add
1474 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1475 * when finding touched windows.
1476 * This test serves as a sanity check for the next test, where setInputWindows is
1477 * called twice.
1478 */
1479TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001480 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001481 sp<FakeWindowHandle> window =
1482 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1483 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001484 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001485
1486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001488 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1489 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001491
1492 // Window should receive motion event.
1493 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1494}
1495
1496/**
1497 * Calling setInputWindows twice, with the same info, should not cause any issues.
1498 * To ensure that window receives only events that were directly inside of it, add
1499 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1500 * when finding touched windows.
1501 */
1502TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001504 sp<FakeWindowHandle> window =
1505 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1506 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001507 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001508
1509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1513 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001515
1516 // Window should receive motion event.
1517 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1518}
1519
Arthur Hungb92218b2018-08-14 12:00:21 +08001520// The foreground window should receive the first touch down event.
1521TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001522 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001523 sp<FakeWindowHandle> windowTop =
1524 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1525 sp<FakeWindowHandle> windowSecond =
1526 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001527
Arthur Hung72d8dc32020-03-28 00:48:39 +00001528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001532
1533 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001534 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001535 windowSecond->assertNoEvents();
1536}
1537
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001538/**
1539 * Two windows: A top window, and a wallpaper behind the window.
1540 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1541 * gets ACTION_CANCEL.
1542 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1543 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1544 */
1545TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1546 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1547 sp<FakeWindowHandle> foregroundWindow =
1548 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1549 foregroundWindow->setHasWallpaper(true);
1550 sp<FakeWindowHandle> wallpaperWindow =
1551 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1552 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1553 constexpr int expectedWallpaperFlags =
1554 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1555
1556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1559 {100, 200}))
1560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1561
1562 // Both foreground window and its wallpaper should receive the touch down
1563 foregroundWindow->consumeMotionDown();
1564 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1565
1566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1567 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1568 ADISPLAY_ID_DEFAULT, {110, 200}))
1569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1570
1571 foregroundWindow->consumeMotionMove();
1572 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1573
1574 // Now the foreground window goes away, but the wallpaper stays
1575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1576 foregroundWindow->consumeMotionCancel();
1577 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1578 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1579}
1580
1581/**
1582 * A single window that receives touch (on top), and a wallpaper window underneath it.
1583 * The top window gets a multitouch gesture.
1584 * Ensure that wallpaper gets the same gesture.
1585 */
1586TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1587 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1588 sp<FakeWindowHandle> window =
1589 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1590 window->setHasWallpaper(true);
1591
1592 sp<FakeWindowHandle> wallpaperWindow =
1593 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1594 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1595 constexpr int expectedWallpaperFlags =
1596 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1597
1598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1599
1600 // Touch down on top window
1601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1602 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1603 {100, 100}))
1604 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1605
1606 // Both top window and its wallpaper should receive the touch down
1607 window->consumeMotionDown();
1608 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1609
1610 // Second finger down on the top window
1611 const MotionEvent secondFingerDownEvent =
1612 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1613 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1614 AINPUT_SOURCE_TOUCHSCREEN)
1615 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1616 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1617 .x(100)
1618 .y(100))
1619 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1620 .x(150)
1621 .y(150))
1622 .build();
1623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1624 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1625 InputEventInjectionSync::WAIT_FOR_RESULT))
1626 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1627
1628 window->consumeMotionPointerDown(1 /* pointerIndex */);
1629 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1630 expectedWallpaperFlags);
1631 window->assertNoEvents();
1632 wallpaperWindow->assertNoEvents();
1633}
1634
1635/**
1636 * Two windows: a window on the left and window on the right.
1637 * A third window, wallpaper, is behind both windows, and spans both top windows.
1638 * The first touch down goes to the left window. A second pointer touches down on the right window.
1639 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1640 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1641 * ACTION_POINTER_DOWN(1).
1642 */
1643TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1645 sp<FakeWindowHandle> leftWindow =
1646 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1647 leftWindow->setFrame(Rect(0, 0, 200, 200));
1648 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1649 leftWindow->setHasWallpaper(true);
1650
1651 sp<FakeWindowHandle> rightWindow =
1652 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1653 rightWindow->setFrame(Rect(200, 0, 400, 200));
1654 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1655 rightWindow->setHasWallpaper(true);
1656
1657 sp<FakeWindowHandle> wallpaperWindow =
1658 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1659 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1660 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1661 constexpr int expectedWallpaperFlags =
1662 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1663
1664 mDispatcher->setInputWindows(
1665 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1666
1667 // Touch down on left window
1668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1669 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1670 {100, 100}))
1671 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1672
1673 // Both foreground window and its wallpaper should receive the touch down
1674 leftWindow->consumeMotionDown();
1675 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1676
1677 // Second finger down on the right window
1678 const MotionEvent secondFingerDownEvent =
1679 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1680 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1681 AINPUT_SOURCE_TOUCHSCREEN)
1682 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1683 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1684 .x(100)
1685 .y(100))
1686 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1687 .x(300)
1688 .y(100))
1689 .build();
1690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1691 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1692 InputEventInjectionSync::WAIT_FOR_RESULT))
1693 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1694
1695 leftWindow->consumeMotionMove();
1696 // Since the touch is split, right window gets ACTION_DOWN
1697 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1698 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1699 expectedWallpaperFlags);
1700
1701 // Now, leftWindow, which received the first finger, disappears.
1702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1703 leftWindow->consumeMotionCancel();
1704 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1705 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1706
1707 // The pointer that's still down on the right window moves, and goes to the right window only.
1708 // As far as the dispatcher's concerned though, both pointers are still present.
1709 const MotionEvent secondFingerMoveEvent =
1710 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1711 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1712 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1713 .x(100)
1714 .y(100))
1715 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1716 .x(310)
1717 .y(110))
1718 .build();
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1721 InputEventInjectionSync::WAIT_FOR_RESULT));
1722 rightWindow->consumeMotionMove();
1723
1724 leftWindow->assertNoEvents();
1725 rightWindow->assertNoEvents();
1726 wallpaperWindow->assertNoEvents();
1727}
1728
Garfield Tandf26e862020-07-01 20:18:19 -07001729TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001730 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001731 sp<FakeWindowHandle> windowLeft =
1732 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1733 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001734 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001735 sp<FakeWindowHandle> windowRight =
1736 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1737 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001738 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001739
1740 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1741
1742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1743
1744 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001746 injectMotionEvent(mDispatcher,
1747 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1748 AINPUT_SOURCE_MOUSE)
1749 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1750 .x(900)
1751 .y(400))
1752 .build()));
1753 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1754 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1755 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1756 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1757
1758 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001760 injectMotionEvent(mDispatcher,
1761 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1762 AINPUT_SOURCE_MOUSE)
1763 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1764 .x(300)
1765 .y(400))
1766 .build()));
1767 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1768 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1769 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1770 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1771 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1772 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1773
1774 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001776 injectMotionEvent(mDispatcher,
1777 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1778 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1779 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1780 .x(300)
1781 .y(400))
1782 .build()));
1783 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1784
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001786 injectMotionEvent(mDispatcher,
1787 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1788 AINPUT_SOURCE_MOUSE)
1789 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1790 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1791 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1792 .x(300)
1793 .y(400))
1794 .build()));
1795 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1796 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1797
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001799 injectMotionEvent(mDispatcher,
1800 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1801 AINPUT_SOURCE_MOUSE)
1802 .buttonState(0)
1803 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1804 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1805 .x(300)
1806 .y(400))
1807 .build()));
1808 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1809 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1810
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001812 injectMotionEvent(mDispatcher,
1813 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1814 .buttonState(0)
1815 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1816 .x(300)
1817 .y(400))
1818 .build()));
1819 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1820
1821 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001823 injectMotionEvent(mDispatcher,
1824 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1825 AINPUT_SOURCE_MOUSE)
1826 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1827 .x(900)
1828 .y(400))
1829 .build()));
1830 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1831 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1832 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1833 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1834 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1835 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1836}
1837
1838// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1839// directly in this test.
1840TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001841 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001842 sp<FakeWindowHandle> window =
1843 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1844 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001845 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001846
1847 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1848
1849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1850
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001852 injectMotionEvent(mDispatcher,
1853 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1854 AINPUT_SOURCE_MOUSE)
1855 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1856 .x(300)
1857 .y(400))
1858 .build()));
1859 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1860 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1861
1862 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001864 injectMotionEvent(mDispatcher,
1865 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1866 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1867 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1868 .x(300)
1869 .y(400))
1870 .build()));
1871 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1872
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001873 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001874 injectMotionEvent(mDispatcher,
1875 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1876 AINPUT_SOURCE_MOUSE)
1877 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1878 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1879 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1880 .x(300)
1881 .y(400))
1882 .build()));
1883 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1884 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001887 injectMotionEvent(mDispatcher,
1888 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1889 AINPUT_SOURCE_MOUSE)
1890 .buttonState(0)
1891 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1892 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1893 .x(300)
1894 .y(400))
1895 .build()));
1896 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1897 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1898
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001900 injectMotionEvent(mDispatcher,
1901 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1902 .buttonState(0)
1903 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1904 .x(300)
1905 .y(400))
1906 .build()));
1907 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1908
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001910 injectMotionEvent(mDispatcher,
1911 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1912 AINPUT_SOURCE_MOUSE)
1913 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1914 .x(300)
1915 .y(400))
1916 .build()));
1917 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1918 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1919}
1920
Garfield Tan00f511d2019-06-12 16:55:40 -07001921TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001922 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001923
1924 sp<FakeWindowHandle> windowLeft =
1925 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1926 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001927 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001928 sp<FakeWindowHandle> windowRight =
1929 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1930 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001931 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001932
1933 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1934
Arthur Hung72d8dc32020-03-28 00:48:39 +00001935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001936
1937 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1938 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001940 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001941 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001942 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001943 windowRight->assertNoEvents();
1944}
1945
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001946TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001947 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001948 sp<FakeWindowHandle> window =
1949 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001950 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001951
Arthur Hung72d8dc32020-03-28 00:48:39 +00001952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001953 setFocusedWindow(window);
1954
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001955 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001956
1957 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1958 mDispatcher->notifyKey(&keyArgs);
1959
1960 // Window should receive key down event.
1961 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1962
1963 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1964 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001965 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001966 mDispatcher->notifyDeviceReset(&args);
1967 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1968 AKEY_EVENT_FLAG_CANCELED);
1969}
1970
1971TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001972 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001973 sp<FakeWindowHandle> window =
1974 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1975
Arthur Hung72d8dc32020-03-28 00:48:39 +00001976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001977
1978 NotifyMotionArgs motionArgs =
1979 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1980 ADISPLAY_ID_DEFAULT);
1981 mDispatcher->notifyMotion(&motionArgs);
1982
1983 // Window should receive motion down event.
1984 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1985
1986 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1987 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001988 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001989 mDispatcher->notifyDeviceReset(&args);
1990 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1991 0 /*expectedFlags*/);
1992}
1993
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001994/**
1995 * Ensure the correct coordinate spaces are used by InputDispatcher.
1996 *
1997 * InputDispatcher works in the display space, so its coordinate system is relative to the display
1998 * panel. Windows get events in the window space, and get raw coordinates in the logical display
1999 * space.
2000 */
2001class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2002public:
2003 void SetUp() override {
2004 InputDispatcherTest::SetUp();
2005 mDisplayInfos.clear();
2006 mWindowInfos.clear();
2007 }
2008
2009 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2010 gui::DisplayInfo info;
2011 info.displayId = displayId;
2012 info.transform = transform;
2013 mDisplayInfos.push_back(std::move(info));
2014 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2015 }
2016
2017 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2018 mWindowInfos.push_back(*windowHandle->getInfo());
2019 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2020 }
2021
2022 // Set up a test scenario where the display has a scaled projection and there are two windows
2023 // on the display.
2024 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2025 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2026 // respectively.
2027 ui::Transform displayTransform;
2028 displayTransform.set(2, 0, 0, 4);
2029 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2030
2031 std::shared_ptr<FakeApplicationHandle> application =
2032 std::make_shared<FakeApplicationHandle>();
2033
2034 // Add two windows to the display. Their frames are represented in the display space.
2035 sp<FakeWindowHandle> firstWindow =
2036 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2037 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2038 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2039 addWindow(firstWindow);
2040
2041 sp<FakeWindowHandle> secondWindow =
2042 new FakeWindowHandle(application, mDispatcher, "Second Window",
2043 ADISPLAY_ID_DEFAULT);
2044 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2045 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2046 addWindow(secondWindow);
2047 return {std::move(firstWindow), std::move(secondWindow)};
2048 }
2049
2050private:
2051 std::vector<gui::DisplayInfo> mDisplayInfos;
2052 std::vector<gui::WindowInfo> mWindowInfos;
2053};
2054
2055TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2056 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2057 // Send down to the first window. The point is represented in the display space. The point is
2058 // selected so that if the hit test was done with the transform applied to it, then it would
2059 // end up in the incorrect window.
2060 NotifyMotionArgs downMotionArgs =
2061 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2062 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2063 mDispatcher->notifyMotion(&downMotionArgs);
2064
2065 firstWindow->consumeMotionDown();
2066 secondWindow->assertNoEvents();
2067}
2068
2069// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2070// the event should be treated as being in the logical display space.
2071TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2072 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2073 // Send down to the first window. The point is represented in the logical display space. The
2074 // point is selected so that if the hit test was done in logical display space, then it would
2075 // end up in the incorrect window.
2076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2077 PointF{75 * 2, 55 * 4});
2078
2079 firstWindow->consumeMotionDown();
2080 secondWindow->assertNoEvents();
2081}
2082
2083TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2084 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2085
2086 // Send down to the second window.
2087 NotifyMotionArgs downMotionArgs =
2088 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2089 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2090 mDispatcher->notifyMotion(&downMotionArgs);
2091
2092 firstWindow->assertNoEvents();
2093 const MotionEvent* event = secondWindow->consumeMotion();
2094 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2095
2096 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2097 EXPECT_EQ(300, event->getRawX(0));
2098 EXPECT_EQ(880, event->getRawY(0));
2099
2100 // Ensure that the x and y values are in the window's coordinate space.
2101 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2102 // the logical display space. This will be the origin of the window space.
2103 EXPECT_EQ(100, event->getX(0));
2104 EXPECT_EQ(80, event->getY(0));
2105}
2106
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002107using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2108 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002109
2110class TransferTouchFixture : public InputDispatcherTest,
2111 public ::testing::WithParamInterface<TransferFunction> {};
2112
2113TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002114 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002115
2116 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002117 sp<FakeWindowHandle> firstWindow =
2118 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2119 sp<FakeWindowHandle> secondWindow =
2120 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002121
2122 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002124
2125 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002126 NotifyMotionArgs downMotionArgs =
2127 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2128 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002129 mDispatcher->notifyMotion(&downMotionArgs);
2130 // Only the first window should get the down event
2131 firstWindow->consumeMotionDown();
2132 secondWindow->assertNoEvents();
2133
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002134 // Transfer touch to the second window
2135 TransferFunction f = GetParam();
2136 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2137 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002138 // The first window gets cancel and the second gets down
2139 firstWindow->consumeMotionCancel();
2140 secondWindow->consumeMotionDown();
2141
2142 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002143 NotifyMotionArgs upMotionArgs =
2144 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2145 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002146 mDispatcher->notifyMotion(&upMotionArgs);
2147 // The first window gets no events and the second gets up
2148 firstWindow->assertNoEvents();
2149 secondWindow->consumeMotionUp();
2150}
2151
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002152TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002153 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002154
2155 PointF touchPoint = {10, 10};
2156
2157 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002158 sp<FakeWindowHandle> firstWindow =
2159 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2160 sp<FakeWindowHandle> secondWindow =
2161 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002162
2163 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002165
2166 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002167 NotifyMotionArgs downMotionArgs =
2168 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2169 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002170 mDispatcher->notifyMotion(&downMotionArgs);
2171 // Only the first window should get the down event
2172 firstWindow->consumeMotionDown();
2173 secondWindow->assertNoEvents();
2174
2175 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002176 NotifyMotionArgs pointerDownMotionArgs =
2177 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2178 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2179 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2180 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002181 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2182 // Only the first window should get the pointer down event
2183 firstWindow->consumeMotionPointerDown(1);
2184 secondWindow->assertNoEvents();
2185
2186 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002187 TransferFunction f = GetParam();
2188 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2189 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002190 // The first window gets cancel and the second gets down and pointer down
2191 firstWindow->consumeMotionCancel();
2192 secondWindow->consumeMotionDown();
2193 secondWindow->consumeMotionPointerDown(1);
2194
2195 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002196 NotifyMotionArgs pointerUpMotionArgs =
2197 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2198 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2199 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2200 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002201 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2202 // The first window gets nothing and the second gets pointer up
2203 firstWindow->assertNoEvents();
2204 secondWindow->consumeMotionPointerUp(1);
2205
2206 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002207 NotifyMotionArgs upMotionArgs =
2208 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2209 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002210 mDispatcher->notifyMotion(&upMotionArgs);
2211 // The first window gets nothing and the second gets up
2212 firstWindow->assertNoEvents();
2213 secondWindow->consumeMotionUp();
2214}
2215
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002216// For the cases of single pointer touch and two pointers non-split touch, the api's
2217// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2218// for the case where there are multiple pointers split across several windows.
2219INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2220 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002221 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2222 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002223 return dispatcher->transferTouch(destChannelToken);
2224 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002225 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2226 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002227 return dispatcher->transferTouchFocus(from, to,
2228 false /*isDragAndDrop*/);
2229 }));
2230
Svet Ganov5d3bc372020-01-26 23:11:07 -08002231TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002232 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002233
2234 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002235 sp<FakeWindowHandle> firstWindow =
2236 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002237 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002238 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002239
2240 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002241 sp<FakeWindowHandle> secondWindow =
2242 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002243 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002244 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002245
2246 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002248
2249 PointF pointInFirst = {300, 200};
2250 PointF pointInSecond = {300, 600};
2251
2252 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002253 NotifyMotionArgs firstDownMotionArgs =
2254 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2255 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002256 mDispatcher->notifyMotion(&firstDownMotionArgs);
2257 // Only the first window should get the down event
2258 firstWindow->consumeMotionDown();
2259 secondWindow->assertNoEvents();
2260
2261 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002262 NotifyMotionArgs secondDownMotionArgs =
2263 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2264 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2265 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2266 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002267 mDispatcher->notifyMotion(&secondDownMotionArgs);
2268 // The first window gets a move and the second a down
2269 firstWindow->consumeMotionMove();
2270 secondWindow->consumeMotionDown();
2271
2272 // Transfer touch focus to the second window
2273 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2274 // The first window gets cancel and the new gets pointer down (it already saw down)
2275 firstWindow->consumeMotionCancel();
2276 secondWindow->consumeMotionPointerDown(1);
2277
2278 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002279 NotifyMotionArgs pointerUpMotionArgs =
2280 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2281 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2282 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2283 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002284 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2285 // The first window gets nothing and the second gets pointer up
2286 firstWindow->assertNoEvents();
2287 secondWindow->consumeMotionPointerUp(1);
2288
2289 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002290 NotifyMotionArgs upMotionArgs =
2291 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2292 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002293 mDispatcher->notifyMotion(&upMotionArgs);
2294 // The first window gets nothing and the second gets up
2295 firstWindow->assertNoEvents();
2296 secondWindow->consumeMotionUp();
2297}
2298
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002299// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2300// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2301// touch is not supported, so the touch should continue on those windows and the transferred-to
2302// window should get nothing.
2303TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2305
2306 // Create a non touch modal window that supports split touch
2307 sp<FakeWindowHandle> firstWindow =
2308 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2309 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002310 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002311
2312 // Create a non touch modal window that supports split touch
2313 sp<FakeWindowHandle> secondWindow =
2314 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2315 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002316 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002317
2318 // Add the windows to the dispatcher
2319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2320
2321 PointF pointInFirst = {300, 200};
2322 PointF pointInSecond = {300, 600};
2323
2324 // Send down to the first window
2325 NotifyMotionArgs firstDownMotionArgs =
2326 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2327 ADISPLAY_ID_DEFAULT, {pointInFirst});
2328 mDispatcher->notifyMotion(&firstDownMotionArgs);
2329 // Only the first window should get the down event
2330 firstWindow->consumeMotionDown();
2331 secondWindow->assertNoEvents();
2332
2333 // Send down to the second window
2334 NotifyMotionArgs secondDownMotionArgs =
2335 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2336 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2337 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2338 {pointInFirst, pointInSecond});
2339 mDispatcher->notifyMotion(&secondDownMotionArgs);
2340 // The first window gets a move and the second a down
2341 firstWindow->consumeMotionMove();
2342 secondWindow->consumeMotionDown();
2343
2344 // Transfer touch focus to the second window
2345 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2346 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2347 ASSERT_FALSE(transferred);
2348 firstWindow->assertNoEvents();
2349 secondWindow->assertNoEvents();
2350
2351 // The rest of the dispatch should proceed as normal
2352 // Send pointer up to the second window
2353 NotifyMotionArgs pointerUpMotionArgs =
2354 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2355 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2356 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2357 {pointInFirst, pointInSecond});
2358 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2359 // The first window gets MOVE and the second gets pointer up
2360 firstWindow->consumeMotionMove();
2361 secondWindow->consumeMotionUp();
2362
2363 // Send up event to the first window
2364 NotifyMotionArgs upMotionArgs =
2365 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2366 ADISPLAY_ID_DEFAULT);
2367 mDispatcher->notifyMotion(&upMotionArgs);
2368 // The first window gets nothing and the second gets up
2369 firstWindow->consumeMotionUp();
2370 secondWindow->assertNoEvents();
2371}
2372
Arthur Hungabbb9d82021-09-01 14:52:30 +00002373// This case will create two windows and one mirrored window on the default display and mirror
2374// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2375// the windows info of second display before default display.
2376TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2377 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2378 sp<FakeWindowHandle> firstWindowInPrimary =
2379 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2380 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2381 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2382 sp<FakeWindowHandle> secondWindowInPrimary =
2383 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2384 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2385 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2386
2387 sp<FakeWindowHandle> mirrorWindowInPrimary =
2388 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2389 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2390 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2391
2392 sp<FakeWindowHandle> firstWindowInSecondary =
2393 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2394 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2395 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2396
2397 sp<FakeWindowHandle> secondWindowInSecondary =
2398 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2399 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2400 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2401
2402 // Update window info, let it find window handle of second display first.
2403 mDispatcher->setInputWindows(
2404 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2405 {ADISPLAY_ID_DEFAULT,
2406 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2407
2408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2410 {50, 50}))
2411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2412
2413 // Window should receive motion event.
2414 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2415
2416 // Transfer touch focus
2417 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2418 secondWindowInPrimary->getToken()));
2419 // The first window gets cancel.
2420 firstWindowInPrimary->consumeMotionCancel();
2421 secondWindowInPrimary->consumeMotionDown();
2422
2423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2424 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2425 ADISPLAY_ID_DEFAULT, {150, 50}))
2426 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2427 firstWindowInPrimary->assertNoEvents();
2428 secondWindowInPrimary->consumeMotionMove();
2429
2430 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2431 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2432 {150, 50}))
2433 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2434 firstWindowInPrimary->assertNoEvents();
2435 secondWindowInPrimary->consumeMotionUp();
2436}
2437
2438// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2439// 'transferTouch' api.
2440TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2441 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2442 sp<FakeWindowHandle> firstWindowInPrimary =
2443 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2444 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2445 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2446 sp<FakeWindowHandle> secondWindowInPrimary =
2447 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2448 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2449 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2450
2451 sp<FakeWindowHandle> mirrorWindowInPrimary =
2452 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2453 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2454 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2455
2456 sp<FakeWindowHandle> firstWindowInSecondary =
2457 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2458 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2459 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2460
2461 sp<FakeWindowHandle> secondWindowInSecondary =
2462 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2463 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2464 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2465
2466 // Update window info, let it find window handle of second display first.
2467 mDispatcher->setInputWindows(
2468 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2469 {ADISPLAY_ID_DEFAULT,
2470 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2471
2472 // Touch on second display.
2473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2474 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2476
2477 // Window should receive motion event.
2478 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2479
2480 // Transfer touch focus
2481 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2482
2483 // The first window gets cancel.
2484 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2485 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2486
2487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2488 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2489 SECOND_DISPLAY_ID, {150, 50}))
2490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2491 firstWindowInPrimary->assertNoEvents();
2492 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2493
2494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2495 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2497 firstWindowInPrimary->assertNoEvents();
2498 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2499}
2500
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002501TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002502 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002503 sp<FakeWindowHandle> window =
2504 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2505
Vishnu Nair47074b82020-08-14 11:54:47 -07002506 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002508 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002509
2510 window->consumeFocusEvent(true);
2511
2512 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2513 mDispatcher->notifyKey(&keyArgs);
2514
2515 // Window should receive key down event.
2516 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2517}
2518
2519TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002520 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002521 sp<FakeWindowHandle> window =
2522 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2523
Arthur Hung72d8dc32020-03-28 00:48:39 +00002524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002525
2526 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2527 mDispatcher->notifyKey(&keyArgs);
2528 mDispatcher->waitForIdle();
2529
2530 window->assertNoEvents();
2531}
2532
2533// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2534TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002536 sp<FakeWindowHandle> window =
2537 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2538
Arthur Hung72d8dc32020-03-28 00:48:39 +00002539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002540
2541 // Send key
2542 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2543 mDispatcher->notifyKey(&keyArgs);
2544 // Send motion
2545 NotifyMotionArgs motionArgs =
2546 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2547 ADISPLAY_ID_DEFAULT);
2548 mDispatcher->notifyMotion(&motionArgs);
2549
2550 // Window should receive only the motion event
2551 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2552 window->assertNoEvents(); // Key event or focus event will not be received
2553}
2554
arthurhungea3f4fc2020-12-21 23:18:53 +08002555TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2556 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2557
2558 // Create first non touch modal window that supports split touch
2559 sp<FakeWindowHandle> firstWindow =
2560 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2561 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002562 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002563
2564 // Create second non touch modal window that supports split touch
2565 sp<FakeWindowHandle> secondWindow =
2566 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2567 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002568 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002569
2570 // Add the windows to the dispatcher
2571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2572
2573 PointF pointInFirst = {300, 200};
2574 PointF pointInSecond = {300, 600};
2575
2576 // Send down to the first window
2577 NotifyMotionArgs firstDownMotionArgs =
2578 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2579 ADISPLAY_ID_DEFAULT, {pointInFirst});
2580 mDispatcher->notifyMotion(&firstDownMotionArgs);
2581 // Only the first window should get the down event
2582 firstWindow->consumeMotionDown();
2583 secondWindow->assertNoEvents();
2584
2585 // Send down to the second window
2586 NotifyMotionArgs secondDownMotionArgs =
2587 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2588 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2589 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2590 {pointInFirst, pointInSecond});
2591 mDispatcher->notifyMotion(&secondDownMotionArgs);
2592 // The first window gets a move and the second a down
2593 firstWindow->consumeMotionMove();
2594 secondWindow->consumeMotionDown();
2595
2596 // Send pointer cancel to the second window
2597 NotifyMotionArgs pointerUpMotionArgs =
2598 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2599 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2600 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2601 {pointInFirst, pointInSecond});
2602 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2603 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2604 // The first window gets move and the second gets cancel.
2605 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2606 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2607
2608 // Send up event.
2609 NotifyMotionArgs upMotionArgs =
2610 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2611 ADISPLAY_ID_DEFAULT);
2612 mDispatcher->notifyMotion(&upMotionArgs);
2613 // The first window gets up and the second gets nothing.
2614 firstWindow->consumeMotionUp();
2615 secondWindow->assertNoEvents();
2616}
2617
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002618TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2620
2621 sp<FakeWindowHandle> window =
2622 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2623 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2624 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2625 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2626 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2627
2628 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2629 window->assertNoEvents();
2630 mDispatcher->waitForIdle();
2631}
2632
chaviwd1c23182019-12-20 18:44:56 -08002633class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002634public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002635 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002636 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002637 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002638 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002639 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002640 }
2641
chaviwd1c23182019-12-20 18:44:56 -08002642 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2643
2644 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2645 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2646 expectedDisplayId, expectedFlags);
2647 }
2648
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002649 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2650
2651 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2652
chaviwd1c23182019-12-20 18:44:56 -08002653 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2654 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2655 expectedDisplayId, expectedFlags);
2656 }
2657
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002658 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2659 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2660 expectedDisplayId, expectedFlags);
2661 }
2662
chaviwd1c23182019-12-20 18:44:56 -08002663 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2664 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2665 expectedDisplayId, expectedFlags);
2666 }
2667
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002668 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2669 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2670 expectedDisplayId, expectedFlags);
2671 }
2672
Evan Rosky84f07f02021-04-16 10:42:42 -07002673 MotionEvent* consumeMotion() {
2674 InputEvent* event = mInputReceiver->consume();
2675 if (!event) {
2676 ADD_FAILURE() << "No event was produced";
2677 return nullptr;
2678 }
2679 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2680 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2681 return nullptr;
2682 }
2683 return static_cast<MotionEvent*>(event);
2684 }
2685
chaviwd1c23182019-12-20 18:44:56 -08002686 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2687
2688private:
2689 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002690};
2691
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002692/**
2693 * Two entities that receive touch: A window, and a global monitor.
2694 * The touch goes to the window, and then the window disappears.
2695 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2696 * for the monitor, as well.
2697 * 1. foregroundWindow
2698 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2699 */
2700TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2702 sp<FakeWindowHandle> window =
2703 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2704
2705 FakeMonitorReceiver monitor =
2706 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2707 false /*isGestureMonitor*/);
2708
2709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2711 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2712 {100, 200}))
2713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2714
2715 // Both the foreground window and the global monitor should receive the touch down
2716 window->consumeMotionDown();
2717 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2718
2719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2720 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2721 ADISPLAY_ID_DEFAULT, {110, 200}))
2722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2723
2724 window->consumeMotionMove();
2725 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2726
2727 // Now the foreground window goes away
2728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2729 window->consumeMotionCancel();
2730 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2731
2732 // If more events come in, there will be no more foreground window to send them to. This will
2733 // cause a cancel for the monitor, as well.
2734 ASSERT_EQ(InputEventInjectionResult::FAILED,
2735 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2736 ADISPLAY_ID_DEFAULT, {120, 200}))
2737 << "Injection should fail because the window was removed";
2738 window->assertNoEvents();
2739 // Global monitor now gets the cancel
2740 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2741}
2742
Michael Wright3a240c42019-12-10 20:53:41 +00002743// Tests for gesture monitors
2744TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002745 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002746 sp<FakeWindowHandle> window =
2747 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002749
chaviwd1c23182019-12-20 18:44:56 -08002750 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2751 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002756 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002757 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002758}
2759
2760TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002762 sp<FakeWindowHandle> window =
2763 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2764
2765 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002766 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002767
Arthur Hung72d8dc32020-03-28 00:48:39 +00002768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002769 setFocusedWindow(window);
2770
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002772
chaviwd1c23182019-12-20 18:44:56 -08002773 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2774 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002775
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2777 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002778 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002779 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002780}
2781
2782TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002783 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002784 sp<FakeWindowHandle> window =
2785 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002787
chaviwd1c23182019-12-20 18:44:56 -08002788 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2789 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002792 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002794 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002795 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002796
2797 window->releaseChannel();
2798
chaviwd1c23182019-12-20 18:44:56 -08002799 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002800
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002802 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002803 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002804 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002805}
2806
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002807TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2808 FakeMonitorReceiver monitor =
2809 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2810 true /*isGestureMonitor*/);
2811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002813 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2814 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2815 ASSERT_TRUE(consumeSeq);
2816
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002817 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002818 monitor.finishEvent(*consumeSeq);
2819 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002820 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002821}
2822
Evan Rosky84f07f02021-04-16 10:42:42 -07002823// Tests for gesture monitors
2824TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2825 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2826 sp<FakeWindowHandle> window =
2827 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2829 window->setWindowOffset(20, 40);
2830 window->setWindowTransform(0, 1, -1, 0);
2831
2832 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2833 true /*isGestureMonitor*/);
2834
2835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2836 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2837 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2838 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2839 MotionEvent* event = monitor.consumeMotion();
2840 // Even though window has transform, gesture monitor must not.
2841 ASSERT_EQ(ui::Transform(), event->getTransform());
2842}
2843
Arthur Hungb3307ee2021-10-14 10:57:37 +00002844TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2845 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2846 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2847 true /*isGestureMonitor*/);
2848
2849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2852 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2853}
2854
chaviw81e2bb92019-12-18 15:03:51 -08002855TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002856 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002857 sp<FakeWindowHandle> window =
2858 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2859
Arthur Hung72d8dc32020-03-28 00:48:39 +00002860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002861
2862 NotifyMotionArgs motionArgs =
2863 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2864 ADISPLAY_ID_DEFAULT);
2865
2866 mDispatcher->notifyMotion(&motionArgs);
2867 // Window should receive motion down event.
2868 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2869
2870 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002871 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002872 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2873 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2874 motionArgs.pointerCoords[0].getX() - 10);
2875
2876 mDispatcher->notifyMotion(&motionArgs);
2877 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2878 0 /*expectedFlags*/);
2879}
2880
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002881/**
2882 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2883 * the device default right away. In the test scenario, we check both the default value,
2884 * and the action of enabling / disabling.
2885 */
2886TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002887 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002888 sp<FakeWindowHandle> window =
2889 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2890
2891 // Set focused application.
2892 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002893 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002894
2895 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002897 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002898 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2899
2900 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002901 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002903 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2904
2905 SCOPED_TRACE("Disable touch mode");
2906 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002907 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002908 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002910 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002911 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2912
2913 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002914 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002916 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2917
2918 SCOPED_TRACE("Enable touch mode again");
2919 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002920 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002921 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002923 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002924 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2925
2926 window->assertNoEvents();
2927}
2928
Gang Wange9087892020-01-07 12:17:14 -05002929TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002930 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002931 sp<FakeWindowHandle> window =
2932 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2933
2934 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002935 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002936
Arthur Hung72d8dc32020-03-28 00:48:39 +00002937 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002938 setFocusedWindow(window);
2939
Gang Wange9087892020-01-07 12:17:14 -05002940 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2941
2942 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2943 mDispatcher->notifyKey(&keyArgs);
2944
2945 InputEvent* event = window->consume();
2946 ASSERT_NE(event, nullptr);
2947
2948 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2949 ASSERT_NE(verified, nullptr);
2950 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2951
2952 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2953 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2954 ASSERT_EQ(keyArgs.source, verified->source);
2955 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2956
2957 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2958
2959 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2960 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002961 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2962 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2963 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2964 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2965 ASSERT_EQ(0, verifiedKey.repeatCount);
2966}
2967
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002968TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002969 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002970 sp<FakeWindowHandle> window =
2971 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2972
2973 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2974
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07002975 ui::Transform transform;
2976 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
2977
2978 gui::DisplayInfo displayInfo;
2979 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
2980 displayInfo.transform = transform;
2981
2982 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002983
2984 NotifyMotionArgs motionArgs =
2985 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2986 ADISPLAY_ID_DEFAULT);
2987 mDispatcher->notifyMotion(&motionArgs);
2988
2989 InputEvent* event = window->consume();
2990 ASSERT_NE(event, nullptr);
2991
2992 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2993 ASSERT_NE(verified, nullptr);
2994 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2995
2996 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2997 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2998 EXPECT_EQ(motionArgs.source, verified->source);
2999 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3000
3001 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3002
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003003 const vec2 rawXY =
3004 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3005 motionArgs.pointerCoords[0].getXYValue());
3006 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3007 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003008 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3009 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3010 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3011 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3012 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3013}
3014
chaviw09c8d2d2020-08-24 15:48:26 -07003015/**
3016 * Ensure that separate calls to sign the same data are generating the same key.
3017 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3018 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3019 * tests.
3020 */
3021TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3022 KeyEvent event = getTestKeyEvent();
3023 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3024
3025 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3026 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3027 ASSERT_EQ(hmac1, hmac2);
3028}
3029
3030/**
3031 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3032 */
3033TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3034 KeyEvent event = getTestKeyEvent();
3035 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3036 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3037
3038 verifiedEvent.deviceId += 1;
3039 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3040
3041 verifiedEvent.source += 1;
3042 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3043
3044 verifiedEvent.eventTimeNanos += 1;
3045 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3046
3047 verifiedEvent.displayId += 1;
3048 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3049
3050 verifiedEvent.action += 1;
3051 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3052
3053 verifiedEvent.downTimeNanos += 1;
3054 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3055
3056 verifiedEvent.flags += 1;
3057 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3058
3059 verifiedEvent.keyCode += 1;
3060 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3061
3062 verifiedEvent.scanCode += 1;
3063 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3064
3065 verifiedEvent.metaState += 1;
3066 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3067
3068 verifiedEvent.repeatCount += 1;
3069 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3070}
3071
Vishnu Nair958da932020-08-21 17:12:37 -07003072TEST_F(InputDispatcherTest, SetFocusedWindow) {
3073 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3074 sp<FakeWindowHandle> windowTop =
3075 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3076 sp<FakeWindowHandle> windowSecond =
3077 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3079
3080 // Top window is also focusable but is not granted focus.
3081 windowTop->setFocusable(true);
3082 windowSecond->setFocusable(true);
3083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3084 setFocusedWindow(windowSecond);
3085
3086 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3088 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003089
3090 // Focused window should receive event.
3091 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3092 windowTop->assertNoEvents();
3093}
3094
3095TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3096 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3097 sp<FakeWindowHandle> window =
3098 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3099 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3100
3101 window->setFocusable(true);
3102 // Release channel for window is no longer valid.
3103 window->releaseChannel();
3104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3105 setFocusedWindow(window);
3106
3107 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003108 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3109 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003110
3111 // window channel is invalid, so it should not receive any input event.
3112 window->assertNoEvents();
3113}
3114
3115TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3116 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3117 sp<FakeWindowHandle> window =
3118 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3119 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3120
3121 // Window is not focusable.
3122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3123 setFocusedWindow(window);
3124
3125 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003126 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3127 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003128
3129 // window is invalid, so it should not receive any input event.
3130 window->assertNoEvents();
3131}
3132
3133TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3134 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3135 sp<FakeWindowHandle> windowTop =
3136 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3137 sp<FakeWindowHandle> windowSecond =
3138 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3139 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3140
3141 windowTop->setFocusable(true);
3142 windowSecond->setFocusable(true);
3143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3144 setFocusedWindow(windowTop);
3145 windowTop->consumeFocusEvent(true);
3146
3147 setFocusedWindow(windowSecond, windowTop);
3148 windowSecond->consumeFocusEvent(true);
3149 windowTop->consumeFocusEvent(false);
3150
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3152 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003153
3154 // Focused window should receive event.
3155 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3156}
3157
3158TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3159 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3160 sp<FakeWindowHandle> windowTop =
3161 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3162 sp<FakeWindowHandle> windowSecond =
3163 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3164 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3165
3166 windowTop->setFocusable(true);
3167 windowSecond->setFocusable(true);
3168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3169 setFocusedWindow(windowSecond, windowTop);
3170
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003171 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3172 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003173
3174 // Event should be dropped.
3175 windowTop->assertNoEvents();
3176 windowSecond->assertNoEvents();
3177}
3178
3179TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3181 sp<FakeWindowHandle> window =
3182 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3183 sp<FakeWindowHandle> previousFocusedWindow =
3184 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3185 ADISPLAY_ID_DEFAULT);
3186 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3187
3188 window->setFocusable(true);
3189 previousFocusedWindow->setFocusable(true);
3190 window->setVisible(false);
3191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3192 setFocusedWindow(previousFocusedWindow);
3193 previousFocusedWindow->consumeFocusEvent(true);
3194
3195 // Requesting focus on invisible window takes focus from currently focused window.
3196 setFocusedWindow(window);
3197 previousFocusedWindow->consumeFocusEvent(false);
3198
3199 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003201 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003202 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003203
3204 // Window does not get focus event or key down.
3205 window->assertNoEvents();
3206
3207 // Window becomes visible.
3208 window->setVisible(true);
3209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3210
3211 // Window receives focus event.
3212 window->consumeFocusEvent(true);
3213 // Focused window receives key down.
3214 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3215}
3216
Vishnu Nair599f1412021-06-21 10:39:58 -07003217TEST_F(InputDispatcherTest, DisplayRemoved) {
3218 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3219 sp<FakeWindowHandle> window =
3220 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3221 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3222
3223 // window is granted focus.
3224 window->setFocusable(true);
3225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3226 setFocusedWindow(window);
3227 window->consumeFocusEvent(true);
3228
3229 // When a display is removed window loses focus.
3230 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3231 window->consumeFocusEvent(false);
3232}
3233
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003234/**
3235 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3236 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3237 * of the 'slipperyEnterWindow'.
3238 *
3239 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3240 * a way so that the touched location is no longer covered by the top window.
3241 *
3242 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3243 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3244 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3245 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3246 * with ACTION_DOWN).
3247 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3248 * window moved itself away from the touched location and had Flag::SLIPPERY.
3249 *
3250 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3251 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3252 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3253 *
3254 * In this test, we ensure that the event received by the bottom window has
3255 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3256 */
3257TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3258 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3259 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3260
3261 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3262 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3263
3264 sp<FakeWindowHandle> slipperyExitWindow =
3265 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003266 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003267 // Make sure this one overlaps the bottom window
3268 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3269 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3270 // one. Windows with the same owner are not considered to be occluding each other.
3271 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3272
3273 sp<FakeWindowHandle> slipperyEnterWindow =
3274 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3275 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3276
3277 mDispatcher->setInputWindows(
3278 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3279
3280 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3281 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3282 ADISPLAY_ID_DEFAULT, {{50, 50}});
3283 mDispatcher->notifyMotion(&args);
3284 slipperyExitWindow->consumeMotionDown();
3285 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3286 mDispatcher->setInputWindows(
3287 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3288
3289 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3290 ADISPLAY_ID_DEFAULT, {{51, 51}});
3291 mDispatcher->notifyMotion(&args);
3292
3293 slipperyExitWindow->consumeMotionCancel();
3294
3295 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3296 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3297}
3298
Garfield Tan1c7bc862020-01-28 13:24:04 -08003299class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3300protected:
3301 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3302 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3303
Chris Yea209fde2020-07-22 13:54:51 -07003304 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003305 sp<FakeWindowHandle> mWindow;
3306
3307 virtual void SetUp() override {
3308 mFakePolicy = new FakeInputDispatcherPolicy();
3309 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003310 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003311 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3312 ASSERT_EQ(OK, mDispatcher->start());
3313
3314 setUpWindow();
3315 }
3316
3317 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003318 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003319 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3320
Vishnu Nair47074b82020-08-14 11:54:47 -07003321 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003323 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003324 mWindow->consumeFocusEvent(true);
3325 }
3326
Chris Ye2ad95392020-09-01 13:44:44 -07003327 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003328 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003329 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003330 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3331 mDispatcher->notifyKey(&keyArgs);
3332
3333 // Window should receive key down event.
3334 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3335 }
3336
3337 void expectKeyRepeatOnce(int32_t repeatCount) {
3338 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3339 InputEvent* repeatEvent = mWindow->consume();
3340 ASSERT_NE(nullptr, repeatEvent);
3341
3342 uint32_t eventType = repeatEvent->getType();
3343 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3344
3345 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3346 uint32_t eventAction = repeatKeyEvent->getAction();
3347 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3348 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3349 }
3350
Chris Ye2ad95392020-09-01 13:44:44 -07003351 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003352 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003353 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003354 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3355 mDispatcher->notifyKey(&keyArgs);
3356
3357 // Window should receive key down event.
3358 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3359 0 /*expectedFlags*/);
3360 }
3361};
3362
3363TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003364 sendAndConsumeKeyDown(1 /* deviceId */);
3365 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3366 expectKeyRepeatOnce(repeatCount);
3367 }
3368}
3369
3370TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3371 sendAndConsumeKeyDown(1 /* deviceId */);
3372 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3373 expectKeyRepeatOnce(repeatCount);
3374 }
3375 sendAndConsumeKeyDown(2 /* deviceId */);
3376 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003377 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3378 expectKeyRepeatOnce(repeatCount);
3379 }
3380}
3381
3382TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003383 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003384 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003385 sendAndConsumeKeyUp(1 /* deviceId */);
3386 mWindow->assertNoEvents();
3387}
3388
3389TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3390 sendAndConsumeKeyDown(1 /* deviceId */);
3391 expectKeyRepeatOnce(1 /*repeatCount*/);
3392 sendAndConsumeKeyDown(2 /* deviceId */);
3393 expectKeyRepeatOnce(1 /*repeatCount*/);
3394 // Stale key up from device 1.
3395 sendAndConsumeKeyUp(1 /* deviceId */);
3396 // Device 2 is still down, keep repeating
3397 expectKeyRepeatOnce(2 /*repeatCount*/);
3398 expectKeyRepeatOnce(3 /*repeatCount*/);
3399 // Device 2 key up
3400 sendAndConsumeKeyUp(2 /* deviceId */);
3401 mWindow->assertNoEvents();
3402}
3403
3404TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3405 sendAndConsumeKeyDown(1 /* deviceId */);
3406 expectKeyRepeatOnce(1 /*repeatCount*/);
3407 sendAndConsumeKeyDown(2 /* deviceId */);
3408 expectKeyRepeatOnce(1 /*repeatCount*/);
3409 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3410 sendAndConsumeKeyUp(2 /* deviceId */);
3411 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003412 mWindow->assertNoEvents();
3413}
3414
liushenxiang42232912021-05-21 20:24:09 +08003415TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3416 sendAndConsumeKeyDown(DEVICE_ID);
3417 expectKeyRepeatOnce(1 /*repeatCount*/);
3418 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3419 mDispatcher->notifyDeviceReset(&args);
3420 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3421 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3422 mWindow->assertNoEvents();
3423}
3424
Garfield Tan1c7bc862020-01-28 13:24:04 -08003425TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003426 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003427 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3428 InputEvent* repeatEvent = mWindow->consume();
3429 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3430 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3431 IdGenerator::getSource(repeatEvent->getId()));
3432 }
3433}
3434
3435TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003436 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003437
3438 std::unordered_set<int32_t> idSet;
3439 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3440 InputEvent* repeatEvent = mWindow->consume();
3441 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3442 int32_t id = repeatEvent->getId();
3443 EXPECT_EQ(idSet.end(), idSet.find(id));
3444 idSet.insert(id);
3445 }
3446}
3447
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003448/* Test InputDispatcher for MultiDisplay */
3449class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3450public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003451 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003452 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003453
Chris Yea209fde2020-07-22 13:54:51 -07003454 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003455 windowInPrimary =
3456 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003457
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003458 // Set focus window for primary display, but focused display would be second one.
3459 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003460 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003462 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003463 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003464
Chris Yea209fde2020-07-22 13:54:51 -07003465 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003466 windowInSecondary =
3467 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003468 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003469 // Set focus display to second one.
3470 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3471 // Set focus window for second display.
3472 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003473 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003474 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003475 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003476 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003477 }
3478
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003479 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003480 InputDispatcherTest::TearDown();
3481
Chris Yea209fde2020-07-22 13:54:51 -07003482 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003483 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003484 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003485 windowInSecondary.clear();
3486 }
3487
3488protected:
Chris Yea209fde2020-07-22 13:54:51 -07003489 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003490 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003491 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003492 sp<FakeWindowHandle> windowInSecondary;
3493};
3494
3495TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3496 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003500 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003501 windowInSecondary->assertNoEvents();
3502
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003503 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3505 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3506 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003507 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003508 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003509}
3510
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003511TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003512 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3514 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003515 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003516 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003517 windowInSecondary->assertNoEvents();
3518
3519 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003521 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003522 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003523 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003524
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003525 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003526 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003527
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003528 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003529 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3530 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003531
3532 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003533 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003534 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003535 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003536 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003537 windowInSecondary->assertNoEvents();
3538}
3539
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003540// Test per-display input monitors for motion event.
3541TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003542 FakeMonitorReceiver monitorInPrimary =
3543 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3544 FakeMonitorReceiver monitorInSecondary =
3545 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003546
3547 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3549 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003551 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003552 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003553 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003554 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003555
3556 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003560 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003561 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003562 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003563 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003564
3565 // Test inject a non-pointer motion event.
3566 // If specific a display, it will dispatch to the focused window of particular display,
3567 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3569 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003571 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003572 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003573 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003574 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003575}
3576
3577// Test per-display input monitors for key event.
3578TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003579 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003580 FakeMonitorReceiver monitorInPrimary =
3581 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3582 FakeMonitorReceiver monitorInSecondary =
3583 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003584
3585 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3587 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003589 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003590 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003591 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003592}
3593
Vishnu Nair958da932020-08-21 17:12:37 -07003594TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3595 sp<FakeWindowHandle> secondWindowInPrimary =
3596 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3597 secondWindowInPrimary->setFocusable(true);
3598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3599 setFocusedWindow(secondWindowInPrimary);
3600 windowInPrimary->consumeFocusEvent(false);
3601 secondWindowInPrimary->consumeFocusEvent(true);
3602
3603 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3605 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003606 windowInPrimary->assertNoEvents();
3607 windowInSecondary->assertNoEvents();
3608 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3609}
3610
Jackal Guof9696682018-10-05 12:23:23 +08003611class InputFilterTest : public InputDispatcherTest {
3612protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003613 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3614 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003615 NotifyMotionArgs motionArgs;
3616
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003617 motionArgs =
3618 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003619 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003620 motionArgs =
3621 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003622 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003623 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003624 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003625 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3626 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003627 } else {
3628 mFakePolicy->assertFilterInputEventWasNotCalled();
3629 }
3630 }
3631
3632 void testNotifyKey(bool expectToBeFiltered) {
3633 NotifyKeyArgs keyArgs;
3634
3635 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3636 mDispatcher->notifyKey(&keyArgs);
3637 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3638 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003639 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003640
3641 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003642 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003643 } else {
3644 mFakePolicy->assertFilterInputEventWasNotCalled();
3645 }
3646 }
3647};
3648
3649// Test InputFilter for MotionEvent
3650TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3651 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3652 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3653 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3654
3655 // Enable InputFilter
3656 mDispatcher->setInputFilterEnabled(true);
3657 // Test touch on both primary and second display, and check if both events are filtered.
3658 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3659 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3660
3661 // Disable InputFilter
3662 mDispatcher->setInputFilterEnabled(false);
3663 // Test touch on both primary and second display, and check if both events aren't filtered.
3664 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3665 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3666}
3667
3668// Test InputFilter for KeyEvent
3669TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3670 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3671 testNotifyKey(/*expectToBeFiltered*/ false);
3672
3673 // Enable InputFilter
3674 mDispatcher->setInputFilterEnabled(true);
3675 // Send a key event, and check if it is filtered.
3676 testNotifyKey(/*expectToBeFiltered*/ true);
3677
3678 // Disable InputFilter
3679 mDispatcher->setInputFilterEnabled(false);
3680 // Send a key event, and check if it isn't filtered.
3681 testNotifyKey(/*expectToBeFiltered*/ false);
3682}
3683
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003684// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3685// logical display coordinate space.
3686TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3687 ui::Transform firstDisplayTransform;
3688 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3689 ui::Transform secondDisplayTransform;
3690 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3691
3692 std::vector<gui::DisplayInfo> displayInfos(2);
3693 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3694 displayInfos[0].transform = firstDisplayTransform;
3695 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3696 displayInfos[1].transform = secondDisplayTransform;
3697
3698 mDispatcher->onWindowInfosChanged({}, displayInfos);
3699
3700 // Enable InputFilter
3701 mDispatcher->setInputFilterEnabled(true);
3702
3703 // Ensure the correct transforms are used for the displays.
3704 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3705 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3706}
3707
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003708class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3709protected:
3710 virtual void SetUp() override {
3711 InputDispatcherTest::SetUp();
3712
3713 /**
3714 * We don't need to enable input filter to test the injected event policy, but we enabled it
3715 * here to make the tests more realistic, since this policy only matters when inputfilter is
3716 * on.
3717 */
3718 mDispatcher->setInputFilterEnabled(true);
3719
3720 std::shared_ptr<InputApplicationHandle> application =
3721 std::make_shared<FakeApplicationHandle>();
3722 mWindow =
3723 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3724
3725 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3726 mWindow->setFocusable(true);
3727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3728 setFocusedWindow(mWindow);
3729 mWindow->consumeFocusEvent(true);
3730 }
3731
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003732 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3733 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003734 KeyEvent event;
3735
3736 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3737 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3738 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3739 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3740 const int32_t additionalPolicyFlags =
3741 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3742 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3743 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3744 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3745 policyFlags | additionalPolicyFlags));
3746
3747 InputEvent* received = mWindow->consume();
3748 ASSERT_NE(nullptr, received);
3749 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003750 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3751 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3752 ASSERT_EQ(flags, keyEvent.getFlags());
3753 }
3754
3755 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3756 int32_t flags) {
3757 MotionEvent event;
3758 PointerProperties pointerProperties[1];
3759 PointerCoords pointerCoords[1];
3760 pointerProperties[0].clear();
3761 pointerProperties[0].id = 0;
3762 pointerCoords[0].clear();
3763 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3764 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3765
3766 ui::Transform identityTransform;
3767 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3768 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3769 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3770 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3771 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003772 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003773 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003774 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3775
3776 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3777 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3778 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3779 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3780 policyFlags | additionalPolicyFlags));
3781
3782 InputEvent* received = mWindow->consume();
3783 ASSERT_NE(nullptr, received);
3784 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3785 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3786 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3787 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003788 }
3789
3790private:
3791 sp<FakeWindowHandle> mWindow;
3792};
3793
3794TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003795 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3796 // filter. Without it, the event will no different from a regularly injected event, and the
3797 // injected device id will be overwritten.
3798 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3799 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003800}
3801
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003802TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003803 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003804 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3805 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3806}
3807
3808TEST_F(InputFilterInjectionPolicyTest,
3809 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3810 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3811 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3812 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003813}
3814
3815TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3816 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003817 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003818}
3819
chaviwfd6d3512019-03-25 13:23:49 -07003820class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003821 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003822 InputDispatcherTest::SetUp();
3823
Chris Yea209fde2020-07-22 13:54:51 -07003824 std::shared_ptr<FakeApplicationHandle> application =
3825 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003826 mUnfocusedWindow =
3827 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003828 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3829 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3830 // window.
chaviw3277faf2021-05-19 16:45:23 -05003831 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003832
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003833 mFocusedWindow =
3834 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3835 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003836 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003837
3838 // Set focused application.
3839 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003840 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003841
3842 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003844 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003845 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003846 }
3847
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003848 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003849 InputDispatcherTest::TearDown();
3850
3851 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003852 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003853 }
3854
3855protected:
3856 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003857 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003858 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003859};
3860
3861// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3862// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3863// the onPointerDownOutsideFocus callback.
3864TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003866 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3867 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003869 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003870
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003871 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003872 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3873}
3874
3875// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3876// DOWN on the window that doesn't have focus. Ensure no window received the
3877// onPointerDownOutsideFocus callback.
3878TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003880 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003881 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003882 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003883
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003884 ASSERT_TRUE(mDispatcher->waitForIdle());
3885 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003886}
3887
3888// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3889// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3890TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3892 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003893 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003894 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003895
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003896 ASSERT_TRUE(mDispatcher->waitForIdle());
3897 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003898}
3899
3900// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3901// DOWN on the window that already has focus. Ensure no window received the
3902// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003903TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003906 FOCUSED_WINDOW_TOUCH_POINT))
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
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003914// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3915// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3916TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3917 const MotionEvent event =
3918 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3919 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3920 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3921 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3922 .build();
3923 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3924 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3925 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3926
3927 ASSERT_TRUE(mDispatcher->waitForIdle());
3928 mFakePolicy->assertOnPointerDownWasNotCalled();
3929 // Ensure that the unfocused window did not receive any FOCUS events.
3930 mUnfocusedWindow->assertNoEvents();
3931}
3932
chaviwaf87b3e2019-10-01 16:59:28 -07003933// These tests ensures we can send touch events to a single client when there are multiple input
3934// windows that point to the same client token.
3935class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3936 virtual void SetUp() override {
3937 InputDispatcherTest::SetUp();
3938
Chris Yea209fde2020-07-22 13:54:51 -07003939 std::shared_ptr<FakeApplicationHandle> application =
3940 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003941 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3942 ADISPLAY_ID_DEFAULT);
3943 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3944 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003945 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003946 mWindow1->setFrame(Rect(0, 0, 100, 100));
3947
3948 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3949 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003950 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003951 mWindow2->setFrame(Rect(100, 100, 200, 200));
3952
Arthur Hung72d8dc32020-03-28 00:48:39 +00003953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003954 }
3955
3956protected:
3957 sp<FakeWindowHandle> mWindow1;
3958 sp<FakeWindowHandle> mWindow2;
3959
3960 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003961 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003962 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3963 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003964 }
3965
3966 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3967 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003968 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003969 InputEvent* event = window->consume();
3970
3971 ASSERT_NE(nullptr, event) << name.c_str()
3972 << ": consumer should have returned non-NULL event.";
3973
3974 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3975 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3976 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3977
3978 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003979 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07003980
3981 for (size_t i = 0; i < points.size(); i++) {
3982 float expectedX = points[i].x;
3983 float expectedY = points[i].y;
3984
3985 EXPECT_EQ(expectedX, motionEvent.getX(i))
3986 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3987 << ", got " << motionEvent.getX(i);
3988 EXPECT_EQ(expectedY, motionEvent.getY(i))
3989 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3990 << ", got " << motionEvent.getY(i);
3991 }
3992 }
chaviw9eaa22c2020-07-01 16:21:27 -07003993
3994 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3995 std::vector<PointF> expectedPoints) {
3996 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3997 ADISPLAY_ID_DEFAULT, touchedPoints);
3998 mDispatcher->notifyMotion(&motionArgs);
3999
4000 // Always consume from window1 since it's the window that has the InputReceiver
4001 consumeMotionEvent(mWindow1, action, expectedPoints);
4002 }
chaviwaf87b3e2019-10-01 16:59:28 -07004003};
4004
4005TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4006 // Touch Window 1
4007 PointF touchedPoint = {10, 10};
4008 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004009 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004010
4011 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004012 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004013
4014 // Touch Window 2
4015 touchedPoint = {150, 150};
4016 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004017 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004018}
4019
chaviw9eaa22c2020-07-01 16:21:27 -07004020TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4021 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004022 mWindow2->setWindowScale(0.5f, 0.5f);
4023
4024 // Touch Window 1
4025 PointF touchedPoint = {10, 10};
4026 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004027 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004028 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004029 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004030
4031 // Touch Window 2
4032 touchedPoint = {150, 150};
4033 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004034 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4035 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004036
chaviw9eaa22c2020-07-01 16:21:27 -07004037 // Update the transform so rotation is set
4038 mWindow2->setWindowTransform(0, -1, 1, 0);
4039 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4040 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004041}
4042
chaviw9eaa22c2020-07-01 16:21:27 -07004043TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004044 mWindow2->setWindowScale(0.5f, 0.5f);
4045
4046 // Touch Window 1
4047 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4048 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004049 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004050
4051 // Touch Window 2
4052 int32_t actionPointerDown =
4053 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004054 touchedPoints.push_back(PointF{150, 150});
4055 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4056 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004057
chaviw9eaa22c2020-07-01 16:21:27 -07004058 // Release Window 2
4059 int32_t actionPointerUp =
4060 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4061 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4062 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004063
chaviw9eaa22c2020-07-01 16:21:27 -07004064 // Update the transform so rotation is set for Window 2
4065 mWindow2->setWindowTransform(0, -1, 1, 0);
4066 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4067 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004068}
4069
chaviw9eaa22c2020-07-01 16:21:27 -07004070TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004071 mWindow2->setWindowScale(0.5f, 0.5f);
4072
4073 // Touch Window 1
4074 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4075 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004076 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004077
4078 // Touch Window 2
4079 int32_t actionPointerDown =
4080 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004081 touchedPoints.push_back(PointF{150, 150});
4082 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004083
chaviw9eaa22c2020-07-01 16:21:27 -07004084 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004085
4086 // Move both windows
4087 touchedPoints = {{20, 20}, {175, 175}};
4088 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4089 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4090
chaviw9eaa22c2020-07-01 16:21:27 -07004091 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004092
chaviw9eaa22c2020-07-01 16:21:27 -07004093 // Release Window 2
4094 int32_t actionPointerUp =
4095 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4096 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4097 expectedPoints.pop_back();
4098
4099 // Touch Window 2
4100 mWindow2->setWindowTransform(0, -1, 1, 0);
4101 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4102 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4103
4104 // Move both windows
4105 touchedPoints = {{20, 20}, {175, 175}};
4106 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4107 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4108
4109 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004110}
4111
4112TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4113 mWindow1->setWindowScale(0.5f, 0.5f);
4114
4115 // Touch Window 1
4116 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4117 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004118 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004119
4120 // Touch Window 2
4121 int32_t actionPointerDown =
4122 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004123 touchedPoints.push_back(PointF{150, 150});
4124 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004125
chaviw9eaa22c2020-07-01 16:21:27 -07004126 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004127
4128 // Move both windows
4129 touchedPoints = {{20, 20}, {175, 175}};
4130 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4131 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4132
chaviw9eaa22c2020-07-01 16:21:27 -07004133 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004134}
4135
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004136class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4137 virtual void SetUp() override {
4138 InputDispatcherTest::SetUp();
4139
Chris Yea209fde2020-07-22 13:54:51 -07004140 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004141 mApplication->setDispatchingTimeout(20ms);
4142 mWindow =
4143 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4144 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004145 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004146 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004147 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4148 // window.
chaviw3277faf2021-05-19 16:45:23 -05004149 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004150
4151 // Set focused application.
4152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4153
4154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004155 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004156 mWindow->consumeFocusEvent(true);
4157 }
4158
4159 virtual void TearDown() override {
4160 InputDispatcherTest::TearDown();
4161 mWindow.clear();
4162 }
4163
4164protected:
Chris Yea209fde2020-07-22 13:54:51 -07004165 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004166 sp<FakeWindowHandle> mWindow;
4167 static constexpr PointF WINDOW_LOCATION = {20, 20};
4168
4169 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004171 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4172 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004174 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4175 WINDOW_LOCATION));
4176 }
4177};
4178
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004179// Send a tap and respond, which should not cause an ANR.
4180TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4181 tapOnWindow();
4182 mWindow->consumeMotionDown();
4183 mWindow->consumeMotionUp();
4184 ASSERT_TRUE(mDispatcher->waitForIdle());
4185 mFakePolicy->assertNotifyAnrWasNotCalled();
4186}
4187
4188// Send a regular key and respond, which should not cause an ANR.
4189TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004191 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4192 ASSERT_TRUE(mDispatcher->waitForIdle());
4193 mFakePolicy->assertNotifyAnrWasNotCalled();
4194}
4195
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004196TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4197 mWindow->setFocusable(false);
4198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4199 mWindow->consumeFocusEvent(false);
4200
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004202 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004203 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4204 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004206 // Key will not go to window because we have no focused window.
4207 // The 'no focused window' ANR timer should start instead.
4208
4209 // Now, the focused application goes away.
4210 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4211 // The key should get dropped and there should be no ANR.
4212
4213 ASSERT_TRUE(mDispatcher->waitForIdle());
4214 mFakePolicy->assertNotifyAnrWasNotCalled();
4215}
4216
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004217// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004218// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4219// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004220TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004221 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004222 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4223 WINDOW_LOCATION));
4224
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004225 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4226 ASSERT_TRUE(sequenceNum);
4227 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004228 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004229
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004230 mWindow->finishEvent(*sequenceNum);
4231 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4232 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004233 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004234 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004235}
4236
4237// Send a key to the app and have the app not respond right away.
4238TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4239 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004241 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4242 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004243 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004244 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004245 ASSERT_TRUE(mDispatcher->waitForIdle());
4246}
4247
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004248// We have a focused application, but no focused window
4249TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004250 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4252 mWindow->consumeFocusEvent(false);
4253
4254 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004255 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004256 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4257 WINDOW_LOCATION));
4258 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4259 mDispatcher->waitForIdle();
4260 mFakePolicy->assertNotifyAnrWasNotCalled();
4261
4262 // Once a focused event arrives, we get an ANR for this application
4263 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4264 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004265 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004266 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004267 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004268 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004269 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004270 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004271 ASSERT_TRUE(mDispatcher->waitForIdle());
4272}
4273
4274// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004275// Make sure that we don't notify policy twice about the same ANR.
4276TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004277 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4279 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004280
4281 // Once a focused event arrives, we get an ANR for this application
4282 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4283 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004284 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004285 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004286 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004287 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004288 const std::chrono::duration appTimeout =
4289 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004290 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004291
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004292 std::this_thread::sleep_for(appTimeout);
4293 // ANR should not be raised again. It is up to policy to do that if it desires.
4294 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004295
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004296 // If we now get a focused window, the ANR should stop, but the policy handles that via
4297 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004298 ASSERT_TRUE(mDispatcher->waitForIdle());
4299}
4300
4301// We have a focused application, but no focused window
4302TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004303 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4305 mWindow->consumeFocusEvent(false);
4306
4307 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004308 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004309 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004310 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4311 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004312
4313 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004314 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004315
4316 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004317 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004318 ASSERT_TRUE(mDispatcher->waitForIdle());
4319 mWindow->assertNoEvents();
4320}
4321
4322/**
4323 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4324 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4325 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4326 * the ANR mechanism should still work.
4327 *
4328 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4329 * DOWN event, while not responding on the second one.
4330 */
4331TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4332 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4333 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4334 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4335 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4336 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004338
4339 // Now send ACTION_UP, with identical timestamp
4340 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4341 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4342 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4343 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004345
4346 // We have now sent down and up. Let's consume first event and then ANR on the second.
4347 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4348 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004349 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004350}
4351
4352// If an app is not responding to a key event, gesture monitors should continue to receive
4353// new motion events
4354TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4355 FakeMonitorReceiver monitor =
4356 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4357 true /*isGestureMonitor*/);
4358
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4360 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004363
4364 // Stuck on the ACTION_UP
4365 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004366 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004367
4368 // New tap will go to the gesture monitor, but not to the window
4369 tapOnWindow();
4370 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4371 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4372
4373 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4374 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004375 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004376 mWindow->assertNoEvents();
4377 monitor.assertNoEvents();
4378}
4379
4380// If an app is not responding to a motion event, gesture monitors should continue to receive
4381// new motion events
4382TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4383 FakeMonitorReceiver monitor =
4384 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4385 true /*isGestureMonitor*/);
4386
4387 tapOnWindow();
4388 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4389 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4390
4391 mWindow->consumeMotionDown();
4392 // Stuck on the ACTION_UP
4393 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004394 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004395
4396 // New tap will go to the gesture monitor, but not to the window
4397 tapOnWindow();
4398 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4399 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4400
4401 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4402 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004403 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004404 mWindow->assertNoEvents();
4405 monitor.assertNoEvents();
4406}
4407
4408// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4409// process events, you don't get an anr. When the window later becomes unresponsive again, you
4410// get an ANR again.
4411// 1. tap -> block on ACTION_UP -> receive ANR
4412// 2. consume all pending events (= queue becomes healthy again)
4413// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4414TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4415 tapOnWindow();
4416
4417 mWindow->consumeMotionDown();
4418 // Block on 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 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4422 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004423 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004424 mWindow->assertNoEvents();
4425
4426 tapOnWindow();
4427 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004428 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004429 mWindow->consumeMotionUp();
4430
4431 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004432 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004433 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434 mWindow->assertNoEvents();
4435}
4436
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004437// If a connection remains unresponsive for a while, make sure policy is only notified once about
4438// it.
4439TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004441 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4442 WINDOW_LOCATION));
4443
4444 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004445 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004447 // 'notifyConnectionUnresponsive' should only be called once per connection
4448 mFakePolicy->assertNotifyAnrWasNotCalled();
4449 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004450 mWindow->consumeMotionDown();
4451 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4452 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4453 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004454 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004455 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004456 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457}
4458
4459/**
4460 * If a window is processing a motion event, and then a key event comes in, the key event should
4461 * not to to the focused window until the motion is processed.
4462 *
4463 * Warning!!!
4464 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4465 * and the injection timeout that we specify when injecting the key.
4466 * We must have the injection timeout (10ms) be smaller than
4467 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4468 *
4469 * If that value changes, this test should also change.
4470 */
4471TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4472 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4474
4475 tapOnWindow();
4476 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4477 ASSERT_TRUE(downSequenceNum);
4478 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4479 ASSERT_TRUE(upSequenceNum);
4480 // Don't finish the events yet, and send a key
4481 // Injection will "succeed" because we will eventually give up and send the key to the focused
4482 // window even if motions are still being processed. But because the injection timeout is short,
4483 // we will receive INJECTION_TIMED_OUT as the result.
4484
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4488 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004489 // Key will not be sent to the window, yet, because the window is still processing events
4490 // and the key remains pending, waiting for the touch events to be processed
4491 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4492 ASSERT_FALSE(keySequenceNum);
4493
4494 std::this_thread::sleep_for(500ms);
4495 // if we wait long enough though, dispatcher will give up, and still send the key
4496 // to the focused window, even though we have not yet finished the motion event
4497 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4498 mWindow->finishEvent(*downSequenceNum);
4499 mWindow->finishEvent(*upSequenceNum);
4500}
4501
4502/**
4503 * If a window is processing a motion event, and then a key event comes in, the key event should
4504 * not go to the focused window until the motion is processed.
4505 * If then a new motion comes in, then the pending key event should be going to the currently
4506 * focused window right away.
4507 */
4508TEST_F(InputDispatcherSingleWindowAnr,
4509 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4510 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4512
4513 tapOnWindow();
4514 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4515 ASSERT_TRUE(downSequenceNum);
4516 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4517 ASSERT_TRUE(upSequenceNum);
4518 // Don't finish the events yet, and send a key
4519 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004521 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004523 // At this point, key is still pending, and should not be sent to the application yet.
4524 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4525 ASSERT_FALSE(keySequenceNum);
4526
4527 // Now tap down again. It should cause the pending key to go to the focused window right away.
4528 tapOnWindow();
4529 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4530 // the other events yet. We can finish events in any order.
4531 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4532 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4533 mWindow->consumeMotionDown();
4534 mWindow->consumeMotionUp();
4535 mWindow->assertNoEvents();
4536}
4537
4538class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4539 virtual void SetUp() override {
4540 InputDispatcherTest::SetUp();
4541
Chris Yea209fde2020-07-22 13:54:51 -07004542 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004543 mApplication->setDispatchingTimeout(10ms);
4544 mUnfocusedWindow =
4545 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4546 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4547 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4548 // window.
4549 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004550 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4551 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4552 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553
4554 mFocusedWindow =
4555 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004556 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004557 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004558 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559
4560 // Set focused application.
4561 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004562 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563
4564 // Expect one focus window exist in display.
4565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004566 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567 mFocusedWindow->consumeFocusEvent(true);
4568 }
4569
4570 virtual void TearDown() override {
4571 InputDispatcherTest::TearDown();
4572
4573 mUnfocusedWindow.clear();
4574 mFocusedWindow.clear();
4575 }
4576
4577protected:
Chris Yea209fde2020-07-22 13:54:51 -07004578 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579 sp<FakeWindowHandle> mUnfocusedWindow;
4580 sp<FakeWindowHandle> mFocusedWindow;
4581 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4582 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4583 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4584
4585 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4586
4587 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4588
4589private:
4590 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4593 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004595 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4596 location));
4597 }
4598};
4599
4600// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4601// should be ANR'd first.
4602TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004604 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4605 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004606 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004607 mFocusedWindow->consumeMotionDown();
4608 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4609 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4610 // We consumed all events, so no ANR
4611 ASSERT_TRUE(mDispatcher->waitForIdle());
4612 mFakePolicy->assertNotifyAnrWasNotCalled();
4613
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004615 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4616 FOCUSED_WINDOW_LOCATION));
4617 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4618 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004619
4620 const std::chrono::duration timeout =
4621 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004622 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004623 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4624 // sequence to make it consistent
4625 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004627 mFocusedWindow->consumeMotionDown();
4628 // This cancel is generated because the connection was unresponsive
4629 mFocusedWindow->consumeMotionCancel();
4630 mFocusedWindow->assertNoEvents();
4631 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004633 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004634 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635}
4636
4637// If we have 2 windows with identical timeouts that are both unresponsive,
4638// it doesn't matter which order they should have ANR.
4639// But we should receive ANR for both.
4640TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4641 // Set the timeout for unfocused window to match the focused window
4642 mUnfocusedWindow->setDispatchingTimeout(10ms);
4643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4644
4645 tapOnFocusedWindow();
4646 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004647 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4648 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649
4650 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004651 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4652 mFocusedWindow->getToken() == anrConnectionToken2);
4653 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4654 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655
4656 ASSERT_TRUE(mDispatcher->waitForIdle());
4657 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004658
4659 mFocusedWindow->consumeMotionDown();
4660 mFocusedWindow->consumeMotionUp();
4661 mUnfocusedWindow->consumeMotionOutside();
4662
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004663 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4664 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004665
4666 // Both applications should be marked as responsive, in any order
4667 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4668 mFocusedWindow->getToken() == responsiveToken2);
4669 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4670 mUnfocusedWindow->getToken() == responsiveToken2);
4671 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672}
4673
4674// If a window is already not responding, the second tap on the same window should be ignored.
4675// We should also log an error to account for the dropped event (not tested here).
4676// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4677TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4678 tapOnFocusedWindow();
4679 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4680 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4681 // Receive the events, but don't respond
4682 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4683 ASSERT_TRUE(downEventSequenceNum);
4684 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4685 ASSERT_TRUE(upEventSequenceNum);
4686 const std::chrono::duration timeout =
4687 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004688 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689
4690 // Tap once again
4691 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4694 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004695 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004696 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4697 FOCUSED_WINDOW_LOCATION));
4698 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4699 // valid touch target
4700 mUnfocusedWindow->assertNoEvents();
4701
4702 // Consume the first tap
4703 mFocusedWindow->finishEvent(*downEventSequenceNum);
4704 mFocusedWindow->finishEvent(*upEventSequenceNum);
4705 ASSERT_TRUE(mDispatcher->waitForIdle());
4706 // The second tap did not go to the focused window
4707 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004708 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004709 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 mFakePolicy->assertNotifyAnrWasNotCalled();
4711}
4712
4713// If you tap outside of all windows, there will not be ANR
4714TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004716 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4717 LOCATION_OUTSIDE_ALL_WINDOWS));
4718 ASSERT_TRUE(mDispatcher->waitForIdle());
4719 mFakePolicy->assertNotifyAnrWasNotCalled();
4720}
4721
4722// Since the focused window is paused, tapping on it should not produce any events
4723TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4724 mFocusedWindow->setPaused(true);
4725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4726
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004727 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4729 FOCUSED_WINDOW_LOCATION));
4730
4731 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4732 ASSERT_TRUE(mDispatcher->waitForIdle());
4733 // Should not ANR because the window is paused, and touches shouldn't go to it
4734 mFakePolicy->assertNotifyAnrWasNotCalled();
4735
4736 mFocusedWindow->assertNoEvents();
4737 mUnfocusedWindow->assertNoEvents();
4738}
4739
4740/**
4741 * If a window is processing a motion event, and then a key event comes in, the key event should
4742 * not to to the focused window until the motion is processed.
4743 * If a different window becomes focused at this time, the key should go to that window instead.
4744 *
4745 * Warning!!!
4746 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4747 * and the injection timeout that we specify when injecting the key.
4748 * We must have the injection timeout (10ms) be smaller than
4749 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4750 *
4751 * If that value changes, this test should also change.
4752 */
4753TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4754 // Set a long ANR timeout to prevent it from triggering
4755 mFocusedWindow->setDispatchingTimeout(2s);
4756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4757
4758 tapOnUnfocusedWindow();
4759 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4760 ASSERT_TRUE(downSequenceNum);
4761 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4762 ASSERT_TRUE(upSequenceNum);
4763 // Don't finish the events yet, and send a key
4764 // Injection will succeed because we will eventually give up and send the key to the focused
4765 // window even if motions are still being processed.
4766
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004767 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004769 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4770 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004771 // Key will not be sent to the window, yet, because the window is still processing events
4772 // and the key remains pending, waiting for the touch events to be processed
4773 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4774 ASSERT_FALSE(keySequenceNum);
4775
4776 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004777 mFocusedWindow->setFocusable(false);
4778 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004780 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781
4782 // Focus events should precede the key events
4783 mUnfocusedWindow->consumeFocusEvent(true);
4784 mFocusedWindow->consumeFocusEvent(false);
4785
4786 // Finish the tap events, which should unblock dispatcher
4787 mUnfocusedWindow->finishEvent(*downSequenceNum);
4788 mUnfocusedWindow->finishEvent(*upSequenceNum);
4789
4790 // Now that all queues are cleared and no backlog in the connections, the key event
4791 // can finally go to the newly focused "mUnfocusedWindow".
4792 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4793 mFocusedWindow->assertNoEvents();
4794 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004795 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796}
4797
4798// When the touch stream is split across 2 windows, and one of them does not respond,
4799// then ANR should be raised and the touch should be canceled for the unresponsive window.
4800// The other window should not be affected by that.
4801TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4802 // Touch Window 1
4803 NotifyMotionArgs motionArgs =
4804 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4805 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4806 mDispatcher->notifyMotion(&motionArgs);
4807 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4808 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4809
4810 // Touch Window 2
4811 int32_t actionPointerDown =
4812 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4813
4814 motionArgs =
4815 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4816 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4817 mDispatcher->notifyMotion(&motionArgs);
4818
4819 const std::chrono::duration timeout =
4820 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004821 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822
4823 mUnfocusedWindow->consumeMotionDown();
4824 mFocusedWindow->consumeMotionDown();
4825 // Focused window may or may not receive ACTION_MOVE
4826 // But it should definitely receive ACTION_CANCEL due to the ANR
4827 InputEvent* event;
4828 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4829 ASSERT_TRUE(moveOrCancelSequenceNum);
4830 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4831 ASSERT_NE(nullptr, event);
4832 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4833 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4834 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4835 mFocusedWindow->consumeMotionCancel();
4836 } else {
4837 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4838 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004839 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004840 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004841
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842 mUnfocusedWindow->assertNoEvents();
4843 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004844 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004845}
4846
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004847/**
4848 * If we have no focused window, and a key comes in, we start the ANR timer.
4849 * The focused application should add a focused window before the timer runs out to prevent ANR.
4850 *
4851 * If the user touches another application during this time, the key should be dropped.
4852 * Next, if a new focused window comes in, without toggling the focused application,
4853 * then no ANR should occur.
4854 *
4855 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4856 * but in some cases the policy may not update the focused application.
4857 */
4858TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4859 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4860 std::make_shared<FakeApplicationHandle>();
4861 focusedApplication->setDispatchingTimeout(60ms);
4862 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4863 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4864 mFocusedWindow->setFocusable(false);
4865
4866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4867 mFocusedWindow->consumeFocusEvent(false);
4868
4869 // Send a key. The ANR timer should start because there is no focused window.
4870 // 'focusedApplication' will get blamed if this timer completes.
4871 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004872 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004873 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004874 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4875 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004877
4878 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4879 // then the injected touches won't cause the focused event to get dropped.
4880 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4881 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4882 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4883 // For this test, it means that the key would get delivered to the window once it becomes
4884 // focused.
4885 std::this_thread::sleep_for(10ms);
4886
4887 // Touch unfocused window. This should force the pending key to get dropped.
4888 NotifyMotionArgs motionArgs =
4889 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4890 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4891 mDispatcher->notifyMotion(&motionArgs);
4892
4893 // We do not consume the motion right away, because that would require dispatcher to first
4894 // process (== drop) the key event, and by that time, ANR will be raised.
4895 // Set the focused window first.
4896 mFocusedWindow->setFocusable(true);
4897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4898 setFocusedWindow(mFocusedWindow);
4899 mFocusedWindow->consumeFocusEvent(true);
4900 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4901 // to another application. This could be a bug / behaviour in the policy.
4902
4903 mUnfocusedWindow->consumeMotionDown();
4904
4905 ASSERT_TRUE(mDispatcher->waitForIdle());
4906 // Should not ANR because we actually have a focused window. It was just added too slowly.
4907 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4908}
4909
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004910// These tests ensure we cannot send touch events to a window that's positioned behind a window
4911// that has feature NO_INPUT_CHANNEL.
4912// Layout:
4913// Top (closest to user)
4914// mNoInputWindow (above all windows)
4915// mBottomWindow
4916// Bottom (furthest from user)
4917class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4918 virtual void SetUp() override {
4919 InputDispatcherTest::SetUp();
4920
4921 mApplication = std::make_shared<FakeApplicationHandle>();
4922 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4923 "Window without input channel", ADISPLAY_ID_DEFAULT,
4924 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4925
chaviw3277faf2021-05-19 16:45:23 -05004926 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004927 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4928 // It's perfectly valid for this window to not have an associated input channel
4929
4930 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4931 ADISPLAY_ID_DEFAULT);
4932 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4933
4934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4935 }
4936
4937protected:
4938 std::shared_ptr<FakeApplicationHandle> mApplication;
4939 sp<FakeWindowHandle> mNoInputWindow;
4940 sp<FakeWindowHandle> mBottomWindow;
4941};
4942
4943TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4944 PointF touchedPoint = {10, 10};
4945
4946 NotifyMotionArgs motionArgs =
4947 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4948 ADISPLAY_ID_DEFAULT, {touchedPoint});
4949 mDispatcher->notifyMotion(&motionArgs);
4950
4951 mNoInputWindow->assertNoEvents();
4952 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4953 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4954 // and therefore should prevent mBottomWindow from receiving touches
4955 mBottomWindow->assertNoEvents();
4956}
4957
4958/**
4959 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4960 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4961 */
4962TEST_F(InputDispatcherMultiWindowOcclusionTests,
4963 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4964 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4965 "Window with input channel and NO_INPUT_CHANNEL",
4966 ADISPLAY_ID_DEFAULT);
4967
chaviw3277faf2021-05-19 16:45:23 -05004968 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004969 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4971
4972 PointF touchedPoint = {10, 10};
4973
4974 NotifyMotionArgs motionArgs =
4975 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4976 ADISPLAY_ID_DEFAULT, {touchedPoint});
4977 mDispatcher->notifyMotion(&motionArgs);
4978
4979 mNoInputWindow->assertNoEvents();
4980 mBottomWindow->assertNoEvents();
4981}
4982
Vishnu Nair958da932020-08-21 17:12:37 -07004983class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4984protected:
4985 std::shared_ptr<FakeApplicationHandle> mApp;
4986 sp<FakeWindowHandle> mWindow;
4987 sp<FakeWindowHandle> mMirror;
4988
4989 virtual void SetUp() override {
4990 InputDispatcherTest::SetUp();
4991 mApp = std::make_shared<FakeApplicationHandle>();
4992 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4993 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4994 mWindow->getToken());
4995 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4996 mWindow->setFocusable(true);
4997 mMirror->setFocusable(true);
4998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4999 }
5000};
5001
5002TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5003 // Request focus on a mirrored window
5004 setFocusedWindow(mMirror);
5005
5006 // window gets focused
5007 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005008 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5009 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005010 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5011}
5012
5013// A focused & mirrored window remains focused only if the window and its mirror are both
5014// focusable.
5015TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5016 setFocusedWindow(mMirror);
5017
5018 // window gets focused
5019 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5021 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005022 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5024 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005025 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5026
5027 mMirror->setFocusable(false);
5028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5029
5030 // window loses focus since one of the windows associated with the token in not focusable
5031 mWindow->consumeFocusEvent(false);
5032
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005033 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5034 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005035 mWindow->assertNoEvents();
5036}
5037
5038// A focused & mirrored window remains focused until the window and its mirror both become
5039// invisible.
5040TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5041 setFocusedWindow(mMirror);
5042
5043 // window gets focused
5044 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5046 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005047 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5049 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005050 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5051
5052 mMirror->setVisible(false);
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5054
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5056 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005057 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5059 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005060 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5061
5062 mWindow->setVisible(false);
5063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5064
5065 // window loses focus only after all windows associated with the token become invisible.
5066 mWindow->consumeFocusEvent(false);
5067
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005068 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5069 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005070 mWindow->assertNoEvents();
5071}
5072
5073// A focused & mirrored window remains focused until both windows are removed.
5074TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5075 setFocusedWindow(mMirror);
5076
5077 // window gets focused
5078 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5080 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005081 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5083 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005084 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5085
5086 // single window is removed but the window token remains focused
5087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5088
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5090 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005091 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5093 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005094 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5095
5096 // Both windows are removed
5097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5098 mWindow->consumeFocusEvent(false);
5099
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005100 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5101 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005102 mWindow->assertNoEvents();
5103}
5104
5105// Focus request can be pending until one window becomes visible.
5106TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5107 // Request focus on an invisible mirror.
5108 mWindow->setVisible(false);
5109 mMirror->setVisible(false);
5110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5111 setFocusedWindow(mMirror);
5112
5113 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005115 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005116 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005117
5118 mMirror->setVisible(true);
5119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5120
5121 // window gets focused
5122 mWindow->consumeFocusEvent(true);
5123 // window gets the pending key event
5124 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5125}
Prabir Pradhan99987712020-11-10 18:43:05 -08005126
5127class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5128protected:
5129 std::shared_ptr<FakeApplicationHandle> mApp;
5130 sp<FakeWindowHandle> mWindow;
5131 sp<FakeWindowHandle> mSecondWindow;
5132
5133 void SetUp() override {
5134 InputDispatcherTest::SetUp();
5135 mApp = std::make_shared<FakeApplicationHandle>();
5136 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5137 mWindow->setFocusable(true);
5138 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5139 mSecondWindow->setFocusable(true);
5140
5141 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5142 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5143
5144 setFocusedWindow(mWindow);
5145 mWindow->consumeFocusEvent(true);
5146 }
5147
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005148 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5149 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005150 mDispatcher->notifyPointerCaptureChanged(&args);
5151 }
5152
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005153 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5154 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005155 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005156 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5157 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005158 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005159 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005160 }
5161};
5162
5163TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5164 // Ensure that capture cannot be obtained for unfocused windows.
5165 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5166 mFakePolicy->assertSetPointerCaptureNotCalled();
5167 mSecondWindow->assertNoEvents();
5168
5169 // Ensure that capture can be enabled from the focus window.
5170 requestAndVerifyPointerCapture(mWindow, true);
5171
5172 // Ensure that capture cannot be disabled from a window that does not have capture.
5173 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5174 mFakePolicy->assertSetPointerCaptureNotCalled();
5175
5176 // Ensure that capture can be disabled from the window with capture.
5177 requestAndVerifyPointerCapture(mWindow, false);
5178}
5179
5180TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005181 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005182
5183 setFocusedWindow(mSecondWindow);
5184
5185 // Ensure that the capture disabled event was sent first.
5186 mWindow->consumeCaptureEvent(false);
5187 mWindow->consumeFocusEvent(false);
5188 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005189 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005190
5191 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005192 notifyPointerCaptureChanged({});
5193 notifyPointerCaptureChanged(request);
5194 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005195 mWindow->assertNoEvents();
5196 mSecondWindow->assertNoEvents();
5197 mFakePolicy->assertSetPointerCaptureNotCalled();
5198}
5199
5200TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005201 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005202
5203 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005204 notifyPointerCaptureChanged({});
5205 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005206
5207 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005208 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005209 mWindow->consumeCaptureEvent(false);
5210 mWindow->assertNoEvents();
5211}
5212
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005213TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5214 requestAndVerifyPointerCapture(mWindow, true);
5215
5216 // The first window loses focus.
5217 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005218 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005219 mWindow->consumeCaptureEvent(false);
5220
5221 // Request Pointer Capture from the second window before the notification from InputReader
5222 // arrives.
5223 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005224 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005225
5226 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005227 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005228
5229 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005230 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005231
5232 mSecondWindow->consumeFocusEvent(true);
5233 mSecondWindow->consumeCaptureEvent(true);
5234}
5235
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005236TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5237 // App repeatedly enables and disables capture.
5238 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5239 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5240 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5241 mFakePolicy->assertSetPointerCaptureCalled(false);
5242 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5243 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5244
5245 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5246 // first request is now stale, this should do nothing.
5247 notifyPointerCaptureChanged(firstRequest);
5248 mWindow->assertNoEvents();
5249
5250 // InputReader notifies that the second request was enabled.
5251 notifyPointerCaptureChanged(secondRequest);
5252 mWindow->consumeCaptureEvent(true);
5253}
5254
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005255class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5256protected:
5257 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005258
5259 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5260 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5261
5262 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5263 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5264
5265 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5266 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5267 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5268 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5269 MAXIMUM_OBSCURING_OPACITY);
5270
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005271 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005272 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005273 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005274
5275 sp<FakeWindowHandle> mTouchWindow;
5276
5277 virtual void SetUp() override {
5278 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005279 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005280 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5281 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5282 }
5283
5284 virtual void TearDown() override {
5285 InputDispatcherTest::TearDown();
5286 mTouchWindow.clear();
5287 }
5288
chaviw3277faf2021-05-19 16:45:23 -05005289 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5290 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005291 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005292 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005293 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005294 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005295 return window;
5296 }
5297
5298 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5299 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5300 sp<FakeWindowHandle> window =
5301 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5302 // Generate an arbitrary PID based on the UID
5303 window->setOwnerInfo(1777 + (uid % 10000), uid);
5304 return window;
5305 }
5306
5307 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5308 NotifyMotionArgs args =
5309 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5310 ADISPLAY_ID_DEFAULT, points);
5311 mDispatcher->notifyMotion(&args);
5312 }
5313};
5314
5315TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005316 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005317 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005319
5320 touch();
5321
5322 mTouchWindow->assertNoEvents();
5323}
5324
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005325TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005326 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5327 const sp<FakeWindowHandle>& w =
5328 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5330
5331 touch();
5332
5333 mTouchWindow->assertNoEvents();
5334}
5335
5336TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005337 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5338 const sp<FakeWindowHandle>& w =
5339 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5341
5342 touch();
5343
5344 w->assertNoEvents();
5345}
5346
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005347TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005348 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005350
5351 touch();
5352
5353 mTouchWindow->consumeAnyMotionDown();
5354}
5355
5356TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005357 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005358 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005359 w->setFrame(Rect(0, 0, 50, 50));
5360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005361
5362 touch({PointF{100, 100}});
5363
5364 mTouchWindow->consumeAnyMotionDown();
5365}
5366
5367TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005368 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005369 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5371
5372 touch();
5373
5374 mTouchWindow->consumeAnyMotionDown();
5375}
5376
5377TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5378 const sp<FakeWindowHandle>& w =
5379 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005381
5382 touch();
5383
5384 mTouchWindow->consumeAnyMotionDown();
5385}
5386
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005387TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5388 const sp<FakeWindowHandle>& w =
5389 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5391
5392 touch();
5393
5394 w->assertNoEvents();
5395}
5396
5397/**
5398 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5399 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5400 * window, the occluding window will still receive ACTION_OUTSIDE event.
5401 */
5402TEST_F(InputDispatcherUntrustedTouchesTest,
5403 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5404 const sp<FakeWindowHandle>& w =
5405 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005406 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5408
5409 touch();
5410
5411 w->consumeMotionOutside();
5412}
5413
5414TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5415 const sp<FakeWindowHandle>& w =
5416 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005417 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5419
5420 touch();
5421
5422 InputEvent* event = w->consume();
5423 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5424 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5425 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5426 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5427}
5428
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005429TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005430 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005431 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5432 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5434
5435 touch();
5436
5437 mTouchWindow->consumeAnyMotionDown();
5438}
5439
5440TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5441 const sp<FakeWindowHandle>& w =
5442 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5443 MAXIMUM_OBSCURING_OPACITY);
5444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005445
5446 touch();
5447
5448 mTouchWindow->consumeAnyMotionDown();
5449}
5450
5451TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005452 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005453 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5454 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5456
5457 touch();
5458
5459 mTouchWindow->assertNoEvents();
5460}
5461
5462TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5463 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5464 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005465 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5466 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005467 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005468 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5469 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5471
5472 touch();
5473
5474 mTouchWindow->assertNoEvents();
5475}
5476
5477TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5478 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5479 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005480 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5481 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005482 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005483 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5484 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005485 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5486
5487 touch();
5488
5489 mTouchWindow->consumeAnyMotionDown();
5490}
5491
5492TEST_F(InputDispatcherUntrustedTouchesTest,
5493 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5494 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005495 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5496 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005497 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005498 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5499 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5501
5502 touch();
5503
5504 mTouchWindow->consumeAnyMotionDown();
5505}
5506
5507TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5508 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005509 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5510 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005511 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005512 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5513 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005515
5516 touch();
5517
5518 mTouchWindow->assertNoEvents();
5519}
5520
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005521TEST_F(InputDispatcherUntrustedTouchesTest,
5522 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5523 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005524 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5525 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005526 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005527 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5528 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5530
5531 touch();
5532
5533 mTouchWindow->assertNoEvents();
5534}
5535
5536TEST_F(InputDispatcherUntrustedTouchesTest,
5537 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5538 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005539 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5540 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005541 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005542 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5543 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5545
5546 touch();
5547
5548 mTouchWindow->consumeAnyMotionDown();
5549}
5550
5551TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5552 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005553 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5554 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5556
5557 touch();
5558
5559 mTouchWindow->consumeAnyMotionDown();
5560}
5561
5562TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5563 const sp<FakeWindowHandle>& w =
5564 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5566
5567 touch();
5568
5569 mTouchWindow->consumeAnyMotionDown();
5570}
5571
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005572TEST_F(InputDispatcherUntrustedTouchesTest,
5573 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5574 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5575 const sp<FakeWindowHandle>& w =
5576 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5578
5579 touch();
5580
5581 mTouchWindow->assertNoEvents();
5582}
5583
5584TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5585 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5586 const sp<FakeWindowHandle>& w =
5587 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5589
5590 touch();
5591
5592 mTouchWindow->consumeAnyMotionDown();
5593}
5594
5595TEST_F(InputDispatcherUntrustedTouchesTest,
5596 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5597 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5598 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005599 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5600 OPACITY_ABOVE_THRESHOLD);
5601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5602
5603 touch();
5604
5605 mTouchWindow->consumeAnyMotionDown();
5606}
5607
5608TEST_F(InputDispatcherUntrustedTouchesTest,
5609 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5610 const sp<FakeWindowHandle>& w1 =
5611 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5612 OPACITY_BELOW_THRESHOLD);
5613 const sp<FakeWindowHandle>& w2 =
5614 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5615 OPACITY_BELOW_THRESHOLD);
5616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5617
5618 touch();
5619
5620 mTouchWindow->assertNoEvents();
5621}
5622
5623/**
5624 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5625 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5626 * (which alone would result in allowing touches) does not affect the blocking behavior.
5627 */
5628TEST_F(InputDispatcherUntrustedTouchesTest,
5629 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5630 const sp<FakeWindowHandle>& wB =
5631 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5632 OPACITY_BELOW_THRESHOLD);
5633 const sp<FakeWindowHandle>& wC =
5634 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5635 OPACITY_BELOW_THRESHOLD);
5636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5637
5638 touch();
5639
5640 mTouchWindow->assertNoEvents();
5641}
5642
5643/**
5644 * This test is testing that a window from a different UID but with same application token doesn't
5645 * block the touch. Apps can share the application token for close UI collaboration for example.
5646 */
5647TEST_F(InputDispatcherUntrustedTouchesTest,
5648 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5649 const sp<FakeWindowHandle>& w =
5650 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5651 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5653
5654 touch();
5655
5656 mTouchWindow->consumeAnyMotionDown();
5657}
5658
arthurhungb89ccb02020-12-30 16:19:01 +08005659class InputDispatcherDragTests : public InputDispatcherTest {
5660protected:
5661 std::shared_ptr<FakeApplicationHandle> mApp;
5662 sp<FakeWindowHandle> mWindow;
5663 sp<FakeWindowHandle> mSecondWindow;
5664 sp<FakeWindowHandle> mDragWindow;
5665
5666 void SetUp() override {
5667 InputDispatcherTest::SetUp();
5668 mApp = std::make_shared<FakeApplicationHandle>();
5669 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5670 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005671 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005672
5673 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5674 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005675 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005676
5677 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5679 }
5680
5681 // Start performing drag, we will create a drag window and transfer touch to it.
5682 void performDrag() {
5683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5684 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5685 {50, 50}))
5686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5687
5688 // Window should receive motion event.
5689 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5690
5691 // The drag window covers the entire display
5692 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5693 mDispatcher->setInputWindows(
5694 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5695
5696 // Transfer touch focus to the drag window
5697 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5698 true /* isDragDrop */);
5699 mWindow->consumeMotionCancel();
5700 mDragWindow->consumeMotionDown();
5701 }
arthurhung6d4bed92021-03-17 11:59:33 +08005702
5703 // Start performing drag, we will create a drag window and transfer touch to it.
5704 void performStylusDrag() {
5705 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5706 injectMotionEvent(mDispatcher,
5707 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5708 AINPUT_SOURCE_STYLUS)
5709 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5710 .pointer(PointerBuilder(0,
5711 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5712 .x(50)
5713 .y(50))
5714 .build()));
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 }
arthurhungb89ccb02020-12-30 16:19:01 +08005728};
5729
5730TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5731 performDrag();
5732
5733 // Move on window.
5734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5735 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5736 ADISPLAY_ID_DEFAULT, {50, 50}))
5737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5738 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5739 mWindow->consumeDragEvent(false, 50, 50);
5740 mSecondWindow->assertNoEvents();
5741
5742 // Move to another window.
5743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5744 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5745 ADISPLAY_ID_DEFAULT, {150, 50}))
5746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5747 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5748 mWindow->consumeDragEvent(true, 150, 50);
5749 mSecondWindow->consumeDragEvent(false, 50, 50);
5750
5751 // Move back to original window.
5752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5753 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5754 ADISPLAY_ID_DEFAULT, {50, 50}))
5755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5756 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5757 mWindow->consumeDragEvent(false, 50, 50);
5758 mSecondWindow->consumeDragEvent(true, -50, 50);
5759
5760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5761 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5762 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5763 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5764 mWindow->assertNoEvents();
5765 mSecondWindow->assertNoEvents();
5766}
5767
arthurhungf452d0b2021-01-06 00:19:52 +08005768TEST_F(InputDispatcherDragTests, DragAndDrop) {
5769 performDrag();
5770
5771 // Move on window.
5772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5773 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5774 ADISPLAY_ID_DEFAULT, {50, 50}))
5775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5776 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5777 mWindow->consumeDragEvent(false, 50, 50);
5778 mSecondWindow->assertNoEvents();
5779
5780 // Move to another window.
5781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5782 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5783 ADISPLAY_ID_DEFAULT, {150, 50}))
5784 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5785 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5786 mWindow->consumeDragEvent(true, 150, 50);
5787 mSecondWindow->consumeDragEvent(false, 50, 50);
5788
5789 // drop to another window.
5790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5791 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5792 {150, 50}))
5793 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5794 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5795 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5796 mWindow->assertNoEvents();
5797 mSecondWindow->assertNoEvents();
5798}
5799
arthurhung6d4bed92021-03-17 11:59:33 +08005800TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5801 performStylusDrag();
5802
5803 // Move on window and keep button pressed.
5804 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5805 injectMotionEvent(mDispatcher,
5806 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5807 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5808 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5809 .x(50)
5810 .y(50))
5811 .build()))
5812 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5813 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5814 mWindow->consumeDragEvent(false, 50, 50);
5815 mSecondWindow->assertNoEvents();
5816
5817 // Move to another window and release button, expect to drop item.
5818 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5819 injectMotionEvent(mDispatcher,
5820 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5821 .buttonState(0)
5822 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5823 .x(150)
5824 .y(50))
5825 .build()))
5826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5827 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5828 mWindow->assertNoEvents();
5829 mSecondWindow->assertNoEvents();
5830 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5831
5832 // nothing to the window.
5833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5834 injectMotionEvent(mDispatcher,
5835 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5836 .buttonState(0)
5837 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5838 .x(150)
5839 .y(50))
5840 .build()))
5841 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5842 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5843 mWindow->assertNoEvents();
5844 mSecondWindow->assertNoEvents();
5845}
5846
Arthur Hung6d0571e2021-04-09 20:18:16 +08005847TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5848 performDrag();
5849
5850 // Set second window invisible.
5851 mSecondWindow->setVisible(false);
5852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5853
5854 // Move on window.
5855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5856 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5857 ADISPLAY_ID_DEFAULT, {50, 50}))
5858 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5859 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5860 mWindow->consumeDragEvent(false, 50, 50);
5861 mSecondWindow->assertNoEvents();
5862
5863 // Move to another window.
5864 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5865 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5866 ADISPLAY_ID_DEFAULT, {150, 50}))
5867 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5868 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5869 mWindow->consumeDragEvent(true, 150, 50);
5870 mSecondWindow->assertNoEvents();
5871
5872 // drop to another window.
5873 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5874 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5875 {150, 50}))
5876 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5877 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5878 mFakePolicy->assertDropTargetEquals(nullptr);
5879 mWindow->assertNoEvents();
5880 mSecondWindow->assertNoEvents();
5881}
5882
Vishnu Nair062a8672021-09-03 16:07:44 -07005883class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5884
5885TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5886 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5887 sp<FakeWindowHandle> window =
5888 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5889 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5890 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5891 window->setFocusable(true);
5892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5893 setFocusedWindow(window);
5894 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5895
5896 // With the flag set, window should not get any input
5897 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5898 mDispatcher->notifyKey(&keyArgs);
5899 window->assertNoEvents();
5900
5901 NotifyMotionArgs motionArgs =
5902 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5903 ADISPLAY_ID_DEFAULT);
5904 mDispatcher->notifyMotion(&motionArgs);
5905 window->assertNoEvents();
5906
5907 // With the flag cleared, the window should get input
5908 window->setInputFeatures({});
5909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5910
5911 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5912 mDispatcher->notifyKey(&keyArgs);
5913 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5914
5915 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5916 ADISPLAY_ID_DEFAULT);
5917 mDispatcher->notifyMotion(&motionArgs);
5918 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5919 window->assertNoEvents();
5920}
5921
5922TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5923 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5924 std::make_shared<FakeApplicationHandle>();
5925 sp<FakeWindowHandle> obscuringWindow =
5926 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5927 ADISPLAY_ID_DEFAULT);
5928 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5929 obscuringWindow->setOwnerInfo(111, 111);
5930 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5932 sp<FakeWindowHandle> window =
5933 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5934 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5935 window->setOwnerInfo(222, 222);
5936 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5937 window->setFocusable(true);
5938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5939 setFocusedWindow(window);
5940 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5941
5942 // With the flag set, window should not get any input
5943 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5944 mDispatcher->notifyKey(&keyArgs);
5945 window->assertNoEvents();
5946
5947 NotifyMotionArgs motionArgs =
5948 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5949 ADISPLAY_ID_DEFAULT);
5950 mDispatcher->notifyMotion(&motionArgs);
5951 window->assertNoEvents();
5952
5953 // With the flag cleared, the window should get input
5954 window->setInputFeatures({});
5955 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5956
5957 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5958 mDispatcher->notifyKey(&keyArgs);
5959 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5960
5961 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5962 ADISPLAY_ID_DEFAULT);
5963 mDispatcher->notifyMotion(&motionArgs);
5964 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
5965 window->assertNoEvents();
5966}
5967
5968TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
5969 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5970 std::make_shared<FakeApplicationHandle>();
5971 sp<FakeWindowHandle> obscuringWindow =
5972 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5973 ADISPLAY_ID_DEFAULT);
5974 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5975 obscuringWindow->setOwnerInfo(111, 111);
5976 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5977 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5978 sp<FakeWindowHandle> window =
5979 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5980 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5981 window->setOwnerInfo(222, 222);
5982 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5983 window->setFocusable(true);
5984 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5985 setFocusedWindow(window);
5986 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5987
5988 // With the flag set, window should not get any input
5989 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5990 mDispatcher->notifyKey(&keyArgs);
5991 window->assertNoEvents();
5992
5993 NotifyMotionArgs motionArgs =
5994 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5995 ADISPLAY_ID_DEFAULT);
5996 mDispatcher->notifyMotion(&motionArgs);
5997 window->assertNoEvents();
5998
5999 // When the window is no longer obscured because it went on top, it should get input
6000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6001
6002 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6003 mDispatcher->notifyKey(&keyArgs);
6004 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6005
6006 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6007 ADISPLAY_ID_DEFAULT);
6008 mDispatcher->notifyMotion(&motionArgs);
6009 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6010 window->assertNoEvents();
6011}
6012
Antonio Kantekf16f2832021-09-28 04:39:20 +00006013class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6014protected:
6015 std::shared_ptr<FakeApplicationHandle> mApp;
6016 sp<FakeWindowHandle> mWindow;
6017 sp<FakeWindowHandle> mSecondWindow;
6018
6019 void SetUp() override {
6020 InputDispatcherTest::SetUp();
6021
6022 mApp = std::make_shared<FakeApplicationHandle>();
6023 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6024 mWindow->setFocusable(true);
6025 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6026 mSecondWindow->setFocusable(true);
6027
6028 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6029 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6030
6031 setFocusedWindow(mWindow);
6032 mWindow->consumeFocusEvent(true);
6033 }
6034
6035 void changeAndVerifyTouchMode(bool inTouchMode) {
6036 mDispatcher->setInTouchMode(inTouchMode);
6037 mWindow->consumeTouchModeEvent(inTouchMode);
6038 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6039 }
6040};
6041
6042TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6043 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6044}
6045
6046TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6047 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6048 mWindow->assertNoEvents();
6049 mSecondWindow->assertNoEvents();
6050}
6051
Garfield Tane84e6f92019-08-29 17:28:41 -07006052} // namespace android::inputdispatcher