blob: c5d9e669605dec3f0f49346e50bd0a0dddd19a56 [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) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700222 // If there is an ANR, Dispatcher won't be idle because there are still events
223 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
224 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500225 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
226 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800227 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
228 const std::chrono::time_point start = std::chrono::steady_clock::now();
229 std::optional<T> token =
230 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
231 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500232 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000233 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700234 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800235
236 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
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 Vishniakou7aa3e942021-11-18 09:49:11 -0800246 return *token;
247 }
248
249 template <class T>
250 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
251 std::queue<T>& storage,
252 std::unique_lock<std::mutex>& lock,
253 std::condition_variable& condition)
254 REQUIRES(mLock) {
255 condition.wait_for(lock, timeout,
256 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
257 if (storage.empty()) {
258 ADD_FAILURE() << "Did not receive the expected callback";
259 return std::nullopt;
260 }
261 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500262 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800263 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700264 }
265
266 void assertNotifyAnrWasNotCalled() {
267 std::scoped_lock lock(mLock);
268 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000269 ASSERT_TRUE(mAnrWindowTokens.empty());
270 ASSERT_TRUE(mAnrMonitorPids.empty());
271 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500272 << "ANR was not called, but please also consume the 'connection is responsive' "
273 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000274 ASSERT_TRUE(mResponsiveMonitorPids.empty())
275 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
276 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700277 }
278
Garfield Tan1c7bc862020-01-28 13:24:04 -0800279 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
280 mConfig.keyRepeatTimeout = timeout;
281 mConfig.keyRepeatDelay = delay;
282 }
283
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000284 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800285 std::unique_lock lock(mLock);
286 base::ScopedLockAssertion assumeLocked(mLock);
287
288 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
289 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000290 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800291 enabled;
292 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000293 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
294 << ") to be called.";
295 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800296 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000297 auto request = *mPointerCaptureRequest;
298 mPointerCaptureRequest.reset();
299 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800300 }
301
302 void assertSetPointerCaptureNotCalled() {
303 std::unique_lock lock(mLock);
304 base::ScopedLockAssertion assumeLocked(mLock);
305
306 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000307 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800308 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000309 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800310 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000311 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 }
313
arthurhungf452d0b2021-01-06 00:19:52 +0800314 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
315 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800316 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800317 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800318 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800319 }
320
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800321 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
322 std::unique_lock lock(mLock);
323 base::ScopedLockAssertion assumeLocked(mLock);
324 std::optional<sp<IBinder>> receivedToken =
325 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
326 mNotifyInputChannelBroken);
327 ASSERT_TRUE(receivedToken.has_value());
328 ASSERT_EQ(token, *receivedToken);
329 }
330
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700332 std::mutex mLock;
333 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
334 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
335 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
336 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800337
Prabir Pradhan99987712020-11-10 18:43:05 -0800338 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000339
340 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800341
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700342 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700343 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000344 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
345 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
346 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
347 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700348 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800349 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
350 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700351
arthurhungf452d0b2021-01-06 00:19:52 +0800352 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800353 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800354
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600355 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700356 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800357 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800358 }
359
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000360 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700361 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000362 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700363 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500364 }
365
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000366 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500367 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000368 mAnrMonitorPids.push(pid);
369 mNotifyAnr.notify_all();
370 }
371
372 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
373 std::scoped_lock lock(mLock);
374 mResponsiveWindowTokens.push(connectionToken);
375 mNotifyAnr.notify_all();
376 }
377
378 void notifyMonitorResponsive(int32_t pid) override {
379 std::scoped_lock lock(mLock);
380 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500381 mNotifyAnr.notify_all();
382 }
383
384 void notifyNoFocusedWindowAnr(
385 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
386 std::scoped_lock lock(mLock);
387 mAnrApplications.push(applicationHandle);
388 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800389 }
390
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800391 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
392 std::scoped_lock lock(mLock);
393 mBrokenInputChannels.push(connectionToken);
394 mNotifyInputChannelBroken.notify_all();
395 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600397 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700398
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600399 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700400 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
401 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
402 const std::vector<float>& values) override {}
403
404 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
405 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000406
Chris Yefb552902021-02-03 17:18:37 -0800407 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
408
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600409 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 *outConfig = mConfig;
411 }
412
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600413 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700414 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800415 switch (inputEvent->getType()) {
416 case AINPUT_EVENT_TYPE_KEY: {
417 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800418 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800419 break;
420 }
421
422 case AINPUT_EVENT_TYPE_MOTION: {
423 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800424 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800425 break;
426 }
427 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800428 return true;
429 }
430
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600431 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800432
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600433 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600435 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 return 0;
437 }
438
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600439 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 return false;
441 }
442
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600443 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
444 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700445 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800446 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
447 * essentially a passthrough for notifySwitch.
448 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800449 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
Sean Stoutb4e0a592021-02-23 07:34:53 -0800452 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800454 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
455 return pid == INJECTOR_PID && uid == INJECTOR_UID;
456 }
Jackal Guof9696682018-10-05 12:23:23 +0800457
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600458 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700459 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700460 mOnPointerDownToken = newToken;
461 }
462
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000463 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800464 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000465 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800466 mPointerCaptureChangedCondition.notify_all();
467 }
468
arthurhungf452d0b2021-01-06 00:19:52 +0800469 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
470 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800471 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800472 mDropTargetWindowToken = token;
473 }
474
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700475 void assertFilterInputEventWasCalledInternal(
476 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700477 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800478 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700479 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800480 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800481 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482};
483
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484// --- InputDispatcherTest ---
485
486class InputDispatcherTest : public testing::Test {
487protected:
488 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700489 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800490
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000491 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700493 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800494 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000495 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700496 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800497 }
498
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000499 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700500 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700502 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700504
505 /**
506 * Used for debugging when writing the test
507 */
508 void dumpDispatcherState() {
509 std::string dump;
510 mDispatcher->dump(dump);
511 std::stringstream ss(dump);
512 std::string to;
513
514 while (std::getline(ss, to, '\n')) {
515 ALOGE("%s", to.c_str());
516 }
517 }
Vishnu Nair958da932020-08-21 17:12:37 -0700518
chaviw3277faf2021-05-19 16:45:23 -0500519 void setFocusedWindow(const sp<WindowInfoHandle>& window,
520 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700521 FocusRequest request;
522 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000523 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700524 if (focusedWindow) {
525 request.focusedToken = focusedWindow->getToken();
526 }
527 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
528 request.displayId = window->getInfo()->displayId;
529 mDispatcher->setFocusedWindow(request);
530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531};
532
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
534 KeyEvent event;
535
536 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800537 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
538 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600539 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
540 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800541 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700542 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800543 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800544 << "Should reject key events with undefined action.";
545
546 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800547 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
548 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600549 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800550 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700551 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 << "Should reject key events with ACTION_MULTIPLE.";
554}
555
556TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
557 MotionEvent event;
558 PointerProperties pointerProperties[MAX_POINTERS + 1];
559 PointerCoords pointerCoords[MAX_POINTERS + 1];
560 for (int i = 0; i <= MAX_POINTERS; i++) {
561 pointerProperties[i].clear();
562 pointerProperties[i].id = i;
563 pointerCoords[i].clear();
564 }
565
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800566 // Some constants commonly used below
567 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
568 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
569 constexpr int32_t metaState = AMETA_NONE;
570 constexpr MotionClassification classification = MotionClassification::NONE;
571
chaviw9eaa22c2020-07-01 16:21:27 -0700572 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800573 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800574 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700575 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
576 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700577 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
578 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700579 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800580 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700581 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800582 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800583 << "Should reject motion events with undefined action.";
584
585 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800586 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700587 AMOTION_EVENT_ACTION_POINTER_DOWN |
588 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700589 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
590 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700591 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500592 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800593 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700594 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 << "Should reject motion events with pointer down index too large.";
597
Garfield Tanfbe732e2020-01-24 11:26:14 -0800598 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 AMOTION_EVENT_ACTION_POINTER_DOWN |
600 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700601 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
602 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700606 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with pointer down index too small.";
609
610 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700612 AMOTION_EVENT_ACTION_POINTER_UP |
613 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700614 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
615 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700616 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500617 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800618 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700619 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800620 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 << "Should reject motion events with pointer up index too large.";
622
Garfield Tanfbe732e2020-01-24 11:26:14 -0800623 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700624 AMOTION_EVENT_ACTION_POINTER_UP |
625 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700626 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
627 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700628 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500629 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800630 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700631 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800632 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 << "Should reject motion events with pointer up index too small.";
634
635 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800636 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
637 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700638 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700639 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
640 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800642 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700643 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800644 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 << "Should reject motion events with 0 pointers.";
646
Garfield Tanfbe732e2020-01-24 11:26:14 -0800647 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
648 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700649 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700650 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
651 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700652 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800653 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700654 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800655 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 << "Should reject motion events with more than MAX_POINTERS pointers.";
657
658 // Rejects motion events with invalid pointer ids.
659 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800660 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
661 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700662 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700663 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
664 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700665 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700667 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800668 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 << "Should reject motion events with pointer ids less than 0.";
670
671 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800672 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
673 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700674 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700675 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
676 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700677 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800678 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700679 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800680 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
682
683 // Rejects motion events with duplicate pointer ids.
684 pointerProperties[0].id = 1;
685 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800686 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
687 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700688 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700689 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
690 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700691 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800692 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700693 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800694 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800695 << "Should reject motion events with duplicate pointer ids.";
696}
697
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800698/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
699
700TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
701 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800702 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800703 mDispatcher->notifyConfigurationChanged(&args);
704 ASSERT_TRUE(mDispatcher->waitForIdle());
705
706 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
707}
708
709TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800710 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
711 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800712 mDispatcher->notifySwitch(&args);
713
714 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
715 args.policyFlags |= POLICY_FLAG_TRUSTED;
716 mFakePolicy->assertNotifySwitchWasCalled(args);
717}
718
Arthur Hungb92218b2018-08-14 12:00:21 +0800719// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700720static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700721// Default input dispatching timeout if there is no focused application or paused window
722// from which to determine an appropriate dispatching timeout.
723static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
724 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
725 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800726
727class FakeApplicationHandle : public InputApplicationHandle {
728public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700729 FakeApplicationHandle() {
730 mInfo.name = "Fake Application";
731 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500732 mInfo.dispatchingTimeoutMillis =
733 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700734 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800735 virtual ~FakeApplicationHandle() {}
736
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000737 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700738
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500739 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
740 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700741 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800742};
743
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800744class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800745public:
Garfield Tan15601662020-09-22 15:32:38 -0700746 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800747 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700748 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800749 }
750
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800751 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 InputEvent* event;
753 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
754 if (!consumeSeq) {
755 return nullptr;
756 }
757 finishEvent(*consumeSeq);
758 return event;
759 }
760
761 /**
762 * Receive an event without acknowledging it.
763 * Return the sequence number that could later be used to send finished signal.
764 */
765 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800766 uint32_t consumeSeq;
767 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800768
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800769 std::chrono::time_point start = std::chrono::steady_clock::now();
770 status_t status = WOULD_BLOCK;
771 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800772 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800773 &event);
774 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
775 if (elapsed > 100ms) {
776 break;
777 }
778 }
779
780 if (status == WOULD_BLOCK) {
781 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700782 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800783 }
784
785 if (status != OK) {
786 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700787 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800788 }
789 if (event == nullptr) {
790 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700791 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700793 if (outEvent != nullptr) {
794 *outEvent = event;
795 }
796 return consumeSeq;
797 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800798
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700799 /**
800 * To be used together with "receiveEvent" to complete the consumption of an event.
801 */
802 void finishEvent(uint32_t consumeSeq) {
803 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
804 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800805 }
806
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000807 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
808 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
809 ASSERT_EQ(OK, status);
810 }
811
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000812 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
813 std::optional<int32_t> expectedDisplayId,
814 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815 InputEvent* event = consume();
816
817 ASSERT_NE(nullptr, event) << mName.c_str()
818 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800819 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700820 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800821 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800822
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000823 if (expectedDisplayId.has_value()) {
824 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
825 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826
Tiger Huang8664f8c2018-10-11 19:14:35 +0800827 switch (expectedEventType) {
828 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800829 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
830 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000831 if (expectedFlags.has_value()) {
832 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
833 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800834 break;
835 }
836 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800837 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000838 assertMotionAction(expectedAction, motionEvent.getAction());
839
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000840 if (expectedFlags.has_value()) {
841 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
842 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800843 break;
844 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100845 case AINPUT_EVENT_TYPE_FOCUS: {
846 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
847 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800848 case AINPUT_EVENT_TYPE_CAPTURE: {
849 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
850 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000851 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
852 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
853 }
arthurhungb89ccb02020-12-30 16:19:01 +0800854 case AINPUT_EVENT_TYPE_DRAG: {
855 FAIL() << "Use 'consumeDragEvent' for DRAG events";
856 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800857 default: {
858 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
859 }
860 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800861 }
862
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100863 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
864 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_FOCUS, event->getType())
868 << "Got " << inputEventTypeToString(event->getType())
869 << " event instead of FOCUS event";
870
871 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
872 << mName.c_str() << ": event displayId should always be NONE.";
873
874 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
875 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100876 }
877
Prabir Pradhan99987712020-11-10 18:43:05 -0800878 void consumeCaptureEvent(bool hasCapture) {
879 const InputEvent* event = consume();
880 ASSERT_NE(nullptr, event) << mName.c_str()
881 << ": consumer should have returned non-NULL event.";
882 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
883 << "Got " << inputEventTypeToString(event->getType())
884 << " event instead of CAPTURE event";
885
886 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
887 << mName.c_str() << ": event displayId should always be NONE.";
888
889 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
890 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
891 }
892
arthurhungb89ccb02020-12-30 16:19:01 +0800893 void consumeDragEvent(bool isExiting, float x, float y) {
894 const InputEvent* event = consume();
895 ASSERT_NE(nullptr, event) << mName.c_str()
896 << ": consumer should have returned non-NULL event.";
897 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
898 << "Got " << inputEventTypeToString(event->getType())
899 << " event instead of DRAG event";
900
901 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
902 << mName.c_str() << ": event displayId should always be NONE.";
903
904 const auto& dragEvent = static_cast<const DragEvent&>(*event);
905 EXPECT_EQ(isExiting, dragEvent.isExiting());
906 EXPECT_EQ(x, dragEvent.getX());
907 EXPECT_EQ(y, dragEvent.getY());
908 }
909
Antonio Kantekf16f2832021-09-28 04:39:20 +0000910 void consumeTouchModeEvent(bool inTouchMode) {
911 const InputEvent* event = consume();
912 ASSERT_NE(nullptr, event) << mName.c_str()
913 << ": consumer should have returned non-NULL event.";
914 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
915 << "Got " << inputEventTypeToString(event->getType())
916 << " event instead of TOUCH_MODE event";
917
918 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
919 << mName.c_str() << ": event displayId should always be NONE.";
920 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
921 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
922 }
923
chaviwd1c23182019-12-20 18:44:56 -0800924 void assertNoEvents() {
925 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700926 if (event == nullptr) {
927 return;
928 }
929 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
930 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
931 ADD_FAILURE() << "Received key event "
932 << KeyEvent::actionToString(keyEvent.getAction());
933 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
934 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
935 ADD_FAILURE() << "Received motion event "
936 << MotionEvent::actionToString(motionEvent.getAction());
937 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
938 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
939 ADD_FAILURE() << "Received focus event, hasFocus = "
940 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800941 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
942 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
943 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
944 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000945 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
946 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
947 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
948 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 }
950 FAIL() << mName.c_str()
951 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800952 }
953
954 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
955
956protected:
957 std::unique_ptr<InputConsumer> mConsumer;
958 PreallocatedInputEventFactory mEventFactory;
959
960 std::string mName;
961};
962
chaviw3277faf2021-05-19 16:45:23 -0500963class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800964public:
965 static const int32_t WIDTH = 600;
966 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800967
Chris Yea209fde2020-07-22 13:54:51 -0700968 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700969 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500970 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800971 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500972 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700973 base::Result<std::unique_ptr<InputChannel>> channel =
974 dispatcher->createInputChannel(name);
975 token = (*channel)->getConnectionToken();
976 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800977 }
978
979 inputApplicationHandle->updateInfo();
980 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
981
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500982 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700983 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800984 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500985 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500986 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000987 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.frameLeft = 0;
989 mInfo.frameTop = 0;
990 mInfo.frameRight = WIDTH;
991 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700992 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.globalScaleFactor = 1.0;
994 mInfo.touchableRegion.clear();
995 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
996 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700997 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800998 mInfo.hasWallpaper = false;
999 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001000 mInfo.ownerPid = INJECTOR_PID;
1001 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.displayId = displayId;
1003 }
1004
Arthur Hungabbb9d82021-09-01 14:52:30 +00001005 sp<FakeWindowHandle> clone(
1006 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001007 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001008 sp<FakeWindowHandle> handle =
1009 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1010 displayId, mInfo.token);
1011 return handle;
1012 }
1013
Vishnu Nair47074b82020-08-14 11:54:47 -07001014 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001015
Vishnu Nair958da932020-08-21 17:12:37 -07001016 void setVisible(bool visible) { mInfo.visible = visible; }
1017
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001018 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001019 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001020 }
1021
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001022 void setPaused(bool paused) { mInfo.paused = paused; }
1023
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001024 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1025
chaviw3277faf2021-05-19 16:45:23 -05001026 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001027
Bernardo Rufino7393d172021-02-26 13:56:11 +00001028 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1029
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001030 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001031 mInfo.frameLeft = frame.left;
1032 mInfo.frameTop = frame.top;
1033 mInfo.frameRight = frame.right;
1034 mInfo.frameBottom = frame.bottom;
1035 mInfo.touchableRegion.clear();
1036 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001037
1038 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1039 ui::Transform translate;
1040 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1041 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001042 }
1043
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001044 void setType(WindowInfo::Type type) { mInfo.type = type; }
1045
1046 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1047
chaviw3277faf2021-05-19 16:45:23 -05001048 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001049
chaviw3277faf2021-05-19 16:45:23 -05001050 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001051
chaviw3277faf2021-05-19 16:45:23 -05001052 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001053
chaviw9eaa22c2020-07-01 16:21:27 -07001054 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1055 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1056 }
1057
1058 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001059
yunho.shinf4a80b82020-11-16 21:13:57 +09001060 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1061
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001062 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1063 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1064 expectedFlags);
1065 }
1066
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1068 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1069 }
1070
Svet Ganov5d3bc372020-01-26 23:11:07 -08001071 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001072 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001073 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1074 expectedFlags);
1075 }
1076
1077 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001078 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001079 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1080 expectedFlags);
1081 }
1082
1083 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001084 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001085 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1086 }
1087
1088 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1089 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001090 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1091 expectedFlags);
1092 }
1093
Svet Ganov5d3bc372020-01-26 23:11:07 -08001094 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001095 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1096 int32_t expectedFlags = 0) {
1097 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1098 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001099 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1100 }
1101
1102 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001103 int32_t expectedFlags = 0) {
1104 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1105 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001106 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1107 }
1108
1109 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001110 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001111 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1112 expectedFlags);
1113 }
1114
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001115 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1116 int32_t expectedFlags = 0) {
1117 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1118 expectedFlags);
1119 }
1120
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001121 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1122 ASSERT_NE(mInputReceiver, nullptr)
1123 << "Cannot consume events from a window with no receiver";
1124 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1125 }
1126
Prabir Pradhan99987712020-11-10 18:43:05 -08001127 void consumeCaptureEvent(bool hasCapture) {
1128 ASSERT_NE(mInputReceiver, nullptr)
1129 << "Cannot consume events from a window with no receiver";
1130 mInputReceiver->consumeCaptureEvent(hasCapture);
1131 }
1132
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001133 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1134 std::optional<int32_t> expectedDisplayId,
1135 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001136 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1137 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1138 expectedFlags);
1139 }
1140
arthurhungb89ccb02020-12-30 16:19:01 +08001141 void consumeDragEvent(bool isExiting, float x, float y) {
1142 mInputReceiver->consumeDragEvent(isExiting, x, y);
1143 }
1144
Antonio Kantekf16f2832021-09-28 04:39:20 +00001145 void consumeTouchModeEvent(bool inTouchMode) {
1146 ASSERT_NE(mInputReceiver, nullptr)
1147 << "Cannot consume events from a window with no receiver";
1148 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1149 }
1150
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001151 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001152 if (mInputReceiver == nullptr) {
1153 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1154 return std::nullopt;
1155 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001156 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001157 }
1158
1159 void finishEvent(uint32_t sequenceNum) {
1160 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1161 mInputReceiver->finishEvent(sequenceNum);
1162 }
1163
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001164 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1165 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1166 mInputReceiver->sendTimeline(inputEventId, timeline);
1167 }
1168
chaviwaf87b3e2019-10-01 16:59:28 -07001169 InputEvent* consume() {
1170 if (mInputReceiver == nullptr) {
1171 return nullptr;
1172 }
1173 return mInputReceiver->consume();
1174 }
1175
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001176 MotionEvent* consumeMotion() {
1177 InputEvent* event = consume();
1178 if (event == nullptr) {
1179 ADD_FAILURE() << "Consume failed : no event";
1180 return nullptr;
1181 }
1182 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1183 ADD_FAILURE() << "Instead of motion event, got "
1184 << inputEventTypeToString(event->getType());
1185 return nullptr;
1186 }
1187 return static_cast<MotionEvent*>(event);
1188 }
1189
Arthur Hungb92218b2018-08-14 12:00:21 +08001190 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001191 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001192 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001193 return; // Can't receive events if the window does not have input channel
1194 }
1195 ASSERT_NE(nullptr, mInputReceiver)
1196 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001197 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001198 }
1199
chaviwaf87b3e2019-10-01 16:59:28 -07001200 sp<IBinder> getToken() { return mInfo.token; }
1201
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001202 const std::string& getName() { return mName; }
1203
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001204 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1205 mInfo.ownerPid = ownerPid;
1206 mInfo.ownerUid = ownerUid;
1207 }
1208
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001209 void destroyReceiver() { mInputReceiver = nullptr; }
1210
chaviwd1c23182019-12-20 18:44:56 -08001211private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001212 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001213 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001214 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001215};
1216
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001217std::atomic<int32_t> FakeWindowHandle::sId{1};
1218
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001219static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001220 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001221 int32_t displayId = ADISPLAY_ID_NONE,
1222 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001223 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1224 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001225 KeyEvent event;
1226 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1227
1228 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001229 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001230 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1231 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001232
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001233 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1234 if (!allowKeyRepeat) {
1235 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1236 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001237 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001238 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001239 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001240}
1241
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001242static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001243 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001244 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1245}
1246
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001247// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1248// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1249// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001250static InputEventInjectionResult injectKeyDownNoRepeat(
1251 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001252 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1253 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1254 /* allowKeyRepeat */ false);
1255}
1256
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001257static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001258 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001259 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1260}
1261
Garfield Tandf26e862020-07-01 20:18:19 -07001262class PointerBuilder {
1263public:
1264 PointerBuilder(int32_t id, int32_t toolType) {
1265 mProperties.clear();
1266 mProperties.id = id;
1267 mProperties.toolType = toolType;
1268 mCoords.clear();
1269 }
1270
1271 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1272
1273 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1274
1275 PointerBuilder& axis(int32_t axis, float value) {
1276 mCoords.setAxisValue(axis, value);
1277 return *this;
1278 }
1279
1280 PointerProperties buildProperties() const { return mProperties; }
1281
1282 PointerCoords buildCoords() const { return mCoords; }
1283
1284private:
1285 PointerProperties mProperties;
1286 PointerCoords mCoords;
1287};
1288
1289class MotionEventBuilder {
1290public:
1291 MotionEventBuilder(int32_t action, int32_t source) {
1292 mAction = action;
1293 mSource = source;
1294 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1295 }
1296
1297 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1298 mEventTime = eventTime;
1299 return *this;
1300 }
1301
1302 MotionEventBuilder& displayId(int32_t displayId) {
1303 mDisplayId = displayId;
1304 return *this;
1305 }
1306
1307 MotionEventBuilder& actionButton(int32_t actionButton) {
1308 mActionButton = actionButton;
1309 return *this;
1310 }
1311
arthurhung6d4bed92021-03-17 11:59:33 +08001312 MotionEventBuilder& buttonState(int32_t buttonState) {
1313 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001314 return *this;
1315 }
1316
1317 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1318 mRawXCursorPosition = rawXCursorPosition;
1319 return *this;
1320 }
1321
1322 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1323 mRawYCursorPosition = rawYCursorPosition;
1324 return *this;
1325 }
1326
1327 MotionEventBuilder& pointer(PointerBuilder pointer) {
1328 mPointers.push_back(pointer);
1329 return *this;
1330 }
1331
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001332 MotionEventBuilder& addFlag(uint32_t flags) {
1333 mFlags |= flags;
1334 return *this;
1335 }
1336
Garfield Tandf26e862020-07-01 20:18:19 -07001337 MotionEvent build() {
1338 std::vector<PointerProperties> pointerProperties;
1339 std::vector<PointerCoords> pointerCoords;
1340 for (const PointerBuilder& pointer : mPointers) {
1341 pointerProperties.push_back(pointer.buildProperties());
1342 pointerCoords.push_back(pointer.buildCoords());
1343 }
1344
1345 // Set mouse cursor position for the most common cases to avoid boilerplate.
1346 if (mSource == AINPUT_SOURCE_MOUSE &&
1347 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1348 mPointers.size() == 1) {
1349 mRawXCursorPosition = pointerCoords[0].getX();
1350 mRawYCursorPosition = pointerCoords[0].getY();
1351 }
1352
1353 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001354 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001355 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001356 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001357 mButtonState, MotionClassification::NONE, identityTransform,
1358 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001359 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1360 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001361
1362 return event;
1363 }
1364
1365private:
1366 int32_t mAction;
1367 int32_t mSource;
1368 nsecs_t mEventTime;
1369 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1370 int32_t mActionButton{0};
1371 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001372 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001373 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1374 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1375
1376 std::vector<PointerBuilder> mPointers;
1377};
1378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001379static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001380 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001381 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001382 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001383 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1384 injectionTimeout,
1385 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1386}
1387
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001388static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001389 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
1390 int32_t displayId, const PointF& position,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001391 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001392 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1393 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001394 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001395 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001396 MotionEvent event = MotionEventBuilder(action, source)
1397 .displayId(displayId)
1398 .eventTime(eventTime)
1399 .rawXCursorPosition(cursorPosition.x)
1400 .rawYCursorPosition(cursorPosition.y)
1401 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1402 .x(position.x)
1403 .y(position.y))
1404 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001405
1406 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001407 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001408}
1409
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001410static InputEventInjectionResult injectMotionDown(
1411 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1412 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001413 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001414}
1415
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001416static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001417 int32_t source, int32_t displayId,
1418 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001419 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001420}
1421
Jackal Guof9696682018-10-05 12:23:23 +08001422static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1423 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1424 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001425 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1426 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1427 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001428
1429 return args;
1430}
1431
chaviwd1c23182019-12-20 18:44:56 -08001432static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1433 const std::vector<PointF>& points) {
1434 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001435 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1436 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1437 }
1438
chaviwd1c23182019-12-20 18:44:56 -08001439 PointerProperties pointerProperties[pointerCount];
1440 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001441
chaviwd1c23182019-12-20 18:44:56 -08001442 for (size_t i = 0; i < pointerCount; i++) {
1443 pointerProperties[i].clear();
1444 pointerProperties[i].id = i;
1445 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001446
chaviwd1c23182019-12-20 18:44:56 -08001447 pointerCoords[i].clear();
1448 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1449 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1450 }
Jackal Guof9696682018-10-05 12:23:23 +08001451
1452 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1453 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001454 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001455 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1456 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001457 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1458 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001459 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1460 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001461
1462 return args;
1463}
1464
chaviwd1c23182019-12-20 18:44:56 -08001465static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1466 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1467}
1468
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001469static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1470 const PointerCaptureRequest& request) {
1471 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001472}
1473
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001474/**
1475 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1476 * broken channel.
1477 */
1478TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1479 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1480 sp<FakeWindowHandle> window =
1481 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1482 ADISPLAY_ID_DEFAULT);
1483
1484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1485
1486 // Window closes its channel, but the window remains.
1487 window->destroyReceiver();
1488 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1489}
1490
Arthur Hungb92218b2018-08-14 12:00:21 +08001491TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001492 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001493 sp<FakeWindowHandle> window =
1494 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001495
Arthur Hung72d8dc32020-03-28 00:48:39 +00001496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001500
1501 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001502 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001503}
1504
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001505TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1506 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1507 sp<FakeWindowHandle> window =
1508 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1509
1510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1511 // Inject a MotionEvent to an unknown display.
1512 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1513 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1515
1516 // Window should receive motion event.
1517 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1518}
1519
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001520/**
1521 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1522 * To ensure that window receives only events that were directly inside of it, add
1523 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1524 * when finding touched windows.
1525 * This test serves as a sanity check for the next test, where setInputWindows is
1526 * called twice.
1527 */
1528TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001529 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001530 sp<FakeWindowHandle> window =
1531 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1532 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001533 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001534
1535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1538 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001540
1541 // Window should receive motion event.
1542 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1543}
1544
1545/**
1546 * Calling setInputWindows twice, with the same info, should not cause any issues.
1547 * To ensure that window receives only events that were directly inside of it, add
1548 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1549 * when finding touched windows.
1550 */
1551TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001552 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001553 sp<FakeWindowHandle> window =
1554 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1555 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001556 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001557
1558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1562 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001564
1565 // Window should receive motion event.
1566 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1567}
1568
Arthur Hungb92218b2018-08-14 12:00:21 +08001569// The foreground window should receive the first touch down event.
1570TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001572 sp<FakeWindowHandle> windowTop =
1573 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1574 sp<FakeWindowHandle> windowSecond =
1575 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001576
Arthur Hung72d8dc32020-03-28 00:48:39 +00001577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001578 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1579 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001581
1582 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001583 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001584 windowSecond->assertNoEvents();
1585}
1586
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001587/**
1588 * Two windows: A top window, and a wallpaper behind the window.
1589 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1590 * gets ACTION_CANCEL.
1591 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1592 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1593 */
1594TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1596 sp<FakeWindowHandle> foregroundWindow =
1597 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1598 foregroundWindow->setHasWallpaper(true);
1599 sp<FakeWindowHandle> wallpaperWindow =
1600 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1601 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1602 constexpr int expectedWallpaperFlags =
1603 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1604
1605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1608 {100, 200}))
1609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1610
1611 // Both foreground window and its wallpaper should receive the touch down
1612 foregroundWindow->consumeMotionDown();
1613 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1614
1615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1616 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1617 ADISPLAY_ID_DEFAULT, {110, 200}))
1618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1619
1620 foregroundWindow->consumeMotionMove();
1621 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1622
1623 // Now the foreground window goes away, but the wallpaper stays
1624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1625 foregroundWindow->consumeMotionCancel();
1626 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1627 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1628}
1629
1630/**
1631 * A single window that receives touch (on top), and a wallpaper window underneath it.
1632 * The top window gets a multitouch gesture.
1633 * Ensure that wallpaper gets the same gesture.
1634 */
1635TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1636 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1637 sp<FakeWindowHandle> window =
1638 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1639 window->setHasWallpaper(true);
1640
1641 sp<FakeWindowHandle> wallpaperWindow =
1642 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1643 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1644 constexpr int expectedWallpaperFlags =
1645 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1646
1647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1648
1649 // Touch down on top window
1650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1652 {100, 100}))
1653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1654
1655 // Both top window and its wallpaper should receive the touch down
1656 window->consumeMotionDown();
1657 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1658
1659 // Second finger down on the top window
1660 const MotionEvent secondFingerDownEvent =
1661 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1662 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1663 AINPUT_SOURCE_TOUCHSCREEN)
1664 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1665 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1666 .x(100)
1667 .y(100))
1668 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1669 .x(150)
1670 .y(150))
1671 .build();
1672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1673 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1674 InputEventInjectionSync::WAIT_FOR_RESULT))
1675 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1676
1677 window->consumeMotionPointerDown(1 /* pointerIndex */);
1678 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1679 expectedWallpaperFlags);
1680 window->assertNoEvents();
1681 wallpaperWindow->assertNoEvents();
1682}
1683
1684/**
1685 * Two windows: a window on the left and window on the right.
1686 * A third window, wallpaper, is behind both windows, and spans both top windows.
1687 * The first touch down goes to the left window. A second pointer touches down on the right window.
1688 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1689 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1690 * ACTION_POINTER_DOWN(1).
1691 */
1692TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1693 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1694 sp<FakeWindowHandle> leftWindow =
1695 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1696 leftWindow->setFrame(Rect(0, 0, 200, 200));
1697 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1698 leftWindow->setHasWallpaper(true);
1699
1700 sp<FakeWindowHandle> rightWindow =
1701 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1702 rightWindow->setFrame(Rect(200, 0, 400, 200));
1703 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1704 rightWindow->setHasWallpaper(true);
1705
1706 sp<FakeWindowHandle> wallpaperWindow =
1707 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1708 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1709 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1710 constexpr int expectedWallpaperFlags =
1711 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1712
1713 mDispatcher->setInputWindows(
1714 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1715
1716 // Touch down on left window
1717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1718 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1719 {100, 100}))
1720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1721
1722 // Both foreground window and its wallpaper should receive the touch down
1723 leftWindow->consumeMotionDown();
1724 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1725
1726 // Second finger down on the right window
1727 const MotionEvent secondFingerDownEvent =
1728 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1729 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1730 AINPUT_SOURCE_TOUCHSCREEN)
1731 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1732 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1733 .x(100)
1734 .y(100))
1735 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1736 .x(300)
1737 .y(100))
1738 .build();
1739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1740 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1741 InputEventInjectionSync::WAIT_FOR_RESULT))
1742 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1743
1744 leftWindow->consumeMotionMove();
1745 // Since the touch is split, right window gets ACTION_DOWN
1746 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1747 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1748 expectedWallpaperFlags);
1749
1750 // Now, leftWindow, which received the first finger, disappears.
1751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1752 leftWindow->consumeMotionCancel();
1753 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1754 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1755
1756 // The pointer that's still down on the right window moves, and goes to the right window only.
1757 // As far as the dispatcher's concerned though, both pointers are still present.
1758 const MotionEvent secondFingerMoveEvent =
1759 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1760 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1761 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1762 .x(100)
1763 .y(100))
1764 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1765 .x(310)
1766 .y(110))
1767 .build();
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1770 InputEventInjectionSync::WAIT_FOR_RESULT));
1771 rightWindow->consumeMotionMove();
1772
1773 leftWindow->assertNoEvents();
1774 rightWindow->assertNoEvents();
1775 wallpaperWindow->assertNoEvents();
1776}
1777
Garfield Tandf26e862020-07-01 20:18:19 -07001778TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001779 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001780 sp<FakeWindowHandle> windowLeft =
1781 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1782 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001783 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001784 sp<FakeWindowHandle> windowRight =
1785 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1786 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001787 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001788
1789 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1790
1791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1792
1793 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001795 injectMotionEvent(mDispatcher,
1796 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1797 AINPUT_SOURCE_MOUSE)
1798 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1799 .x(900)
1800 .y(400))
1801 .build()));
1802 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1803 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1804 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1805 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1806
1807 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001808 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001809 injectMotionEvent(mDispatcher,
1810 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1811 AINPUT_SOURCE_MOUSE)
1812 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1813 .x(300)
1814 .y(400))
1815 .build()));
1816 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1817 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1818 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1819 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1820 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1821 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1822
1823 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001824 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001825 injectMotionEvent(mDispatcher,
1826 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1827 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1828 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1829 .x(300)
1830 .y(400))
1831 .build()));
1832 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1833
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001835 injectMotionEvent(mDispatcher,
1836 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1837 AINPUT_SOURCE_MOUSE)
1838 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1839 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1840 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1841 .x(300)
1842 .y(400))
1843 .build()));
1844 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1845 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1846
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001847 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001848 injectMotionEvent(mDispatcher,
1849 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1850 AINPUT_SOURCE_MOUSE)
1851 .buttonState(0)
1852 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1853 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1854 .x(300)
1855 .y(400))
1856 .build()));
1857 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1858 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1859
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001861 injectMotionEvent(mDispatcher,
1862 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1863 .buttonState(0)
1864 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1865 .x(300)
1866 .y(400))
1867 .build()));
1868 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1869
1870 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001872 injectMotionEvent(mDispatcher,
1873 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1874 AINPUT_SOURCE_MOUSE)
1875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1876 .x(900)
1877 .y(400))
1878 .build()));
1879 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1880 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1881 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1882 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1883 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1884 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1885}
1886
1887// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1888// directly in this test.
1889TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001890 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001891 sp<FakeWindowHandle> window =
1892 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1893 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001894 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001895
1896 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1897
1898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1899
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001901 injectMotionEvent(mDispatcher,
1902 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1903 AINPUT_SOURCE_MOUSE)
1904 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1905 .x(300)
1906 .y(400))
1907 .build()));
1908 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1909 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1910
1911 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001913 injectMotionEvent(mDispatcher,
1914 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1915 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1916 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1917 .x(300)
1918 .y(400))
1919 .build()));
1920 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1921
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001923 injectMotionEvent(mDispatcher,
1924 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1925 AINPUT_SOURCE_MOUSE)
1926 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1927 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1928 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1929 .x(300)
1930 .y(400))
1931 .build()));
1932 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1933 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1934
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001936 injectMotionEvent(mDispatcher,
1937 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1938 AINPUT_SOURCE_MOUSE)
1939 .buttonState(0)
1940 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1941 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1942 .x(300)
1943 .y(400))
1944 .build()));
1945 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1946 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1947
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001949 injectMotionEvent(mDispatcher,
1950 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1951 .buttonState(0)
1952 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1953 .x(300)
1954 .y(400))
1955 .build()));
1956 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1957
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001959 injectMotionEvent(mDispatcher,
1960 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1961 AINPUT_SOURCE_MOUSE)
1962 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1963 .x(300)
1964 .y(400))
1965 .build()));
1966 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1967 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1968}
1969
Garfield Tan00f511d2019-06-12 16:55:40 -07001970TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001971 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001972
1973 sp<FakeWindowHandle> windowLeft =
1974 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1975 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001976 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001977 sp<FakeWindowHandle> windowRight =
1978 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1979 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001980 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001981
1982 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1983
Arthur Hung72d8dc32020-03-28 00:48:39 +00001984 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001985
1986 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1987 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001989 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001990 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001991 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001992 windowRight->assertNoEvents();
1993}
1994
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001995TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001997 sp<FakeWindowHandle> window =
1998 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001999 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002000
Arthur Hung72d8dc32020-03-28 00:48:39 +00002001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002002 setFocusedWindow(window);
2003
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002004 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002005
2006 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2007 mDispatcher->notifyKey(&keyArgs);
2008
2009 // Window should receive key down event.
2010 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2011
2012 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2013 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002014 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002015 mDispatcher->notifyDeviceReset(&args);
2016 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2017 AKEY_EVENT_FLAG_CANCELED);
2018}
2019
2020TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002021 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002022 sp<FakeWindowHandle> window =
2023 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2024
Arthur Hung72d8dc32020-03-28 00:48:39 +00002025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002026
2027 NotifyMotionArgs motionArgs =
2028 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2029 ADISPLAY_ID_DEFAULT);
2030 mDispatcher->notifyMotion(&motionArgs);
2031
2032 // Window should receive motion down event.
2033 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2034
2035 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2036 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002037 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002038 mDispatcher->notifyDeviceReset(&args);
2039 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2040 0 /*expectedFlags*/);
2041}
2042
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002043/**
2044 * Ensure the correct coordinate spaces are used by InputDispatcher.
2045 *
2046 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2047 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2048 * space.
2049 */
2050class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2051public:
2052 void SetUp() override {
2053 InputDispatcherTest::SetUp();
2054 mDisplayInfos.clear();
2055 mWindowInfos.clear();
2056 }
2057
2058 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2059 gui::DisplayInfo info;
2060 info.displayId = displayId;
2061 info.transform = transform;
2062 mDisplayInfos.push_back(std::move(info));
2063 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2064 }
2065
2066 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2067 mWindowInfos.push_back(*windowHandle->getInfo());
2068 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2069 }
2070
2071 // Set up a test scenario where the display has a scaled projection and there are two windows
2072 // on the display.
2073 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2074 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2075 // respectively.
2076 ui::Transform displayTransform;
2077 displayTransform.set(2, 0, 0, 4);
2078 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2079
2080 std::shared_ptr<FakeApplicationHandle> application =
2081 std::make_shared<FakeApplicationHandle>();
2082
2083 // Add two windows to the display. Their frames are represented in the display space.
2084 sp<FakeWindowHandle> firstWindow =
2085 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2086 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2087 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2088 addWindow(firstWindow);
2089
2090 sp<FakeWindowHandle> secondWindow =
2091 new FakeWindowHandle(application, mDispatcher, "Second Window",
2092 ADISPLAY_ID_DEFAULT);
2093 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2094 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2095 addWindow(secondWindow);
2096 return {std::move(firstWindow), std::move(secondWindow)};
2097 }
2098
2099private:
2100 std::vector<gui::DisplayInfo> mDisplayInfos;
2101 std::vector<gui::WindowInfo> mWindowInfos;
2102};
2103
2104TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2105 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2106 // Send down to the first window. The point is represented in the display space. The point is
2107 // selected so that if the hit test was done with the transform applied to it, then it would
2108 // end up in the incorrect window.
2109 NotifyMotionArgs downMotionArgs =
2110 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2111 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2112 mDispatcher->notifyMotion(&downMotionArgs);
2113
2114 firstWindow->consumeMotionDown();
2115 secondWindow->assertNoEvents();
2116}
2117
2118// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2119// the event should be treated as being in the logical display space.
2120TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2121 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2122 // Send down to the first window. The point is represented in the logical display space. The
2123 // point is selected so that if the hit test was done in logical display space, then it would
2124 // end up in the incorrect window.
2125 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2126 PointF{75 * 2, 55 * 4});
2127
2128 firstWindow->consumeMotionDown();
2129 secondWindow->assertNoEvents();
2130}
2131
2132TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2133 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2134
2135 // Send down to the second window.
2136 NotifyMotionArgs downMotionArgs =
2137 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2138 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2139 mDispatcher->notifyMotion(&downMotionArgs);
2140
2141 firstWindow->assertNoEvents();
2142 const MotionEvent* event = secondWindow->consumeMotion();
2143 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2144
2145 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2146 EXPECT_EQ(300, event->getRawX(0));
2147 EXPECT_EQ(880, event->getRawY(0));
2148
2149 // Ensure that the x and y values are in the window's coordinate space.
2150 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2151 // the logical display space. This will be the origin of the window space.
2152 EXPECT_EQ(100, event->getX(0));
2153 EXPECT_EQ(80, event->getY(0));
2154}
2155
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002156using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2157 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002158
2159class TransferTouchFixture : public InputDispatcherTest,
2160 public ::testing::WithParamInterface<TransferFunction> {};
2161
2162TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002163 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002164
2165 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002166 sp<FakeWindowHandle> firstWindow =
2167 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2168 sp<FakeWindowHandle> secondWindow =
2169 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002170
2171 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002173
2174 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002175 NotifyMotionArgs downMotionArgs =
2176 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2177 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002178 mDispatcher->notifyMotion(&downMotionArgs);
2179 // Only the first window should get the down event
2180 firstWindow->consumeMotionDown();
2181 secondWindow->assertNoEvents();
2182
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002183 // Transfer touch to the second window
2184 TransferFunction f = GetParam();
2185 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2186 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002187 // The first window gets cancel and the second gets down
2188 firstWindow->consumeMotionCancel();
2189 secondWindow->consumeMotionDown();
2190
2191 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002192 NotifyMotionArgs upMotionArgs =
2193 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2194 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002195 mDispatcher->notifyMotion(&upMotionArgs);
2196 // The first window gets no events and the second gets up
2197 firstWindow->assertNoEvents();
2198 secondWindow->consumeMotionUp();
2199}
2200
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002201TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002202 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002203
2204 PointF touchPoint = {10, 10};
2205
2206 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002207 sp<FakeWindowHandle> firstWindow =
2208 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2209 sp<FakeWindowHandle> secondWindow =
2210 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002211
2212 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002214
2215 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002216 NotifyMotionArgs downMotionArgs =
2217 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2218 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002219 mDispatcher->notifyMotion(&downMotionArgs);
2220 // Only the first window should get the down event
2221 firstWindow->consumeMotionDown();
2222 secondWindow->assertNoEvents();
2223
2224 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002225 NotifyMotionArgs pointerDownMotionArgs =
2226 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2227 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2228 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2229 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002230 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2231 // Only the first window should get the pointer down event
2232 firstWindow->consumeMotionPointerDown(1);
2233 secondWindow->assertNoEvents();
2234
2235 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002236 TransferFunction f = GetParam();
2237 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2238 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002239 // The first window gets cancel and the second gets down and pointer down
2240 firstWindow->consumeMotionCancel();
2241 secondWindow->consumeMotionDown();
2242 secondWindow->consumeMotionPointerDown(1);
2243
2244 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002245 NotifyMotionArgs pointerUpMotionArgs =
2246 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2247 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2248 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2249 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002250 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2251 // The first window gets nothing and the second gets pointer up
2252 firstWindow->assertNoEvents();
2253 secondWindow->consumeMotionPointerUp(1);
2254
2255 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002256 NotifyMotionArgs upMotionArgs =
2257 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2258 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002259 mDispatcher->notifyMotion(&upMotionArgs);
2260 // The first window gets nothing and the second gets up
2261 firstWindow->assertNoEvents();
2262 secondWindow->consumeMotionUp();
2263}
2264
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002265// For the cases of single pointer touch and two pointers non-split touch, the api's
2266// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2267// for the case where there are multiple pointers split across several windows.
2268INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2269 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002270 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2271 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002272 return dispatcher->transferTouch(destChannelToken);
2273 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002274 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2275 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002276 return dispatcher->transferTouchFocus(from, to,
2277 false /*isDragAndDrop*/);
2278 }));
2279
Svet Ganov5d3bc372020-01-26 23:11:07 -08002280TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002282
2283 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002284 sp<FakeWindowHandle> firstWindow =
2285 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002286 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002287 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002288
2289 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002290 sp<FakeWindowHandle> secondWindow =
2291 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002292 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002293 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002294
2295 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002297
2298 PointF pointInFirst = {300, 200};
2299 PointF pointInSecond = {300, 600};
2300
2301 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002302 NotifyMotionArgs firstDownMotionArgs =
2303 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2304 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002305 mDispatcher->notifyMotion(&firstDownMotionArgs);
2306 // Only the first window should get the down event
2307 firstWindow->consumeMotionDown();
2308 secondWindow->assertNoEvents();
2309
2310 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002311 NotifyMotionArgs secondDownMotionArgs =
2312 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2313 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2314 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2315 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002316 mDispatcher->notifyMotion(&secondDownMotionArgs);
2317 // The first window gets a move and the second a down
2318 firstWindow->consumeMotionMove();
2319 secondWindow->consumeMotionDown();
2320
2321 // Transfer touch focus to the second window
2322 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2323 // The first window gets cancel and the new gets pointer down (it already saw down)
2324 firstWindow->consumeMotionCancel();
2325 secondWindow->consumeMotionPointerDown(1);
2326
2327 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002328 NotifyMotionArgs pointerUpMotionArgs =
2329 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2330 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2331 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2332 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002333 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2334 // The first window gets nothing and the second gets pointer up
2335 firstWindow->assertNoEvents();
2336 secondWindow->consumeMotionPointerUp(1);
2337
2338 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002339 NotifyMotionArgs upMotionArgs =
2340 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2341 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002342 mDispatcher->notifyMotion(&upMotionArgs);
2343 // The first window gets nothing and the second gets up
2344 firstWindow->assertNoEvents();
2345 secondWindow->consumeMotionUp();
2346}
2347
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002348// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2349// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2350// touch is not supported, so the touch should continue on those windows and the transferred-to
2351// window should get nothing.
2352TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2353 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2354
2355 // Create a non touch modal window that supports split touch
2356 sp<FakeWindowHandle> firstWindow =
2357 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2358 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002359 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002360
2361 // Create a non touch modal window that supports split touch
2362 sp<FakeWindowHandle> secondWindow =
2363 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2364 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002365 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002366
2367 // Add the windows to the dispatcher
2368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2369
2370 PointF pointInFirst = {300, 200};
2371 PointF pointInSecond = {300, 600};
2372
2373 // Send down to the first window
2374 NotifyMotionArgs firstDownMotionArgs =
2375 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2376 ADISPLAY_ID_DEFAULT, {pointInFirst});
2377 mDispatcher->notifyMotion(&firstDownMotionArgs);
2378 // Only the first window should get the down event
2379 firstWindow->consumeMotionDown();
2380 secondWindow->assertNoEvents();
2381
2382 // Send down to the second window
2383 NotifyMotionArgs secondDownMotionArgs =
2384 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2385 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2386 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2387 {pointInFirst, pointInSecond});
2388 mDispatcher->notifyMotion(&secondDownMotionArgs);
2389 // The first window gets a move and the second a down
2390 firstWindow->consumeMotionMove();
2391 secondWindow->consumeMotionDown();
2392
2393 // Transfer touch focus to the second window
2394 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2395 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2396 ASSERT_FALSE(transferred);
2397 firstWindow->assertNoEvents();
2398 secondWindow->assertNoEvents();
2399
2400 // The rest of the dispatch should proceed as normal
2401 // Send pointer up to the second window
2402 NotifyMotionArgs pointerUpMotionArgs =
2403 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2404 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2405 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2406 {pointInFirst, pointInSecond});
2407 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2408 // The first window gets MOVE and the second gets pointer up
2409 firstWindow->consumeMotionMove();
2410 secondWindow->consumeMotionUp();
2411
2412 // Send up event to the first window
2413 NotifyMotionArgs upMotionArgs =
2414 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2415 ADISPLAY_ID_DEFAULT);
2416 mDispatcher->notifyMotion(&upMotionArgs);
2417 // The first window gets nothing and the second gets up
2418 firstWindow->consumeMotionUp();
2419 secondWindow->assertNoEvents();
2420}
2421
Arthur Hungabbb9d82021-09-01 14:52:30 +00002422// This case will create two windows and one mirrored window on the default display and mirror
2423// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2424// the windows info of second display before default display.
2425TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2426 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2427 sp<FakeWindowHandle> firstWindowInPrimary =
2428 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2429 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2430 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2431 sp<FakeWindowHandle> secondWindowInPrimary =
2432 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2433 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2434 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2435
2436 sp<FakeWindowHandle> mirrorWindowInPrimary =
2437 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2438 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2439 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2440
2441 sp<FakeWindowHandle> firstWindowInSecondary =
2442 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2443 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2444 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2445
2446 sp<FakeWindowHandle> secondWindowInSecondary =
2447 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2448 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2449 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2450
2451 // Update window info, let it find window handle of second display first.
2452 mDispatcher->setInputWindows(
2453 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2454 {ADISPLAY_ID_DEFAULT,
2455 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2456
2457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2458 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2459 {50, 50}))
2460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2461
2462 // Window should receive motion event.
2463 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2464
2465 // Transfer touch focus
2466 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2467 secondWindowInPrimary->getToken()));
2468 // The first window gets cancel.
2469 firstWindowInPrimary->consumeMotionCancel();
2470 secondWindowInPrimary->consumeMotionDown();
2471
2472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2473 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2474 ADISPLAY_ID_DEFAULT, {150, 50}))
2475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2476 firstWindowInPrimary->assertNoEvents();
2477 secondWindowInPrimary->consumeMotionMove();
2478
2479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2480 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2481 {150, 50}))
2482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2483 firstWindowInPrimary->assertNoEvents();
2484 secondWindowInPrimary->consumeMotionUp();
2485}
2486
2487// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2488// 'transferTouch' api.
2489TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2490 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2491 sp<FakeWindowHandle> firstWindowInPrimary =
2492 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2493 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2494 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2495 sp<FakeWindowHandle> secondWindowInPrimary =
2496 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2497 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2498 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2499
2500 sp<FakeWindowHandle> mirrorWindowInPrimary =
2501 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2502 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2503 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2504
2505 sp<FakeWindowHandle> firstWindowInSecondary =
2506 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2507 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2508 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2509
2510 sp<FakeWindowHandle> secondWindowInSecondary =
2511 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2512 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2513 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2514
2515 // Update window info, let it find window handle of second display first.
2516 mDispatcher->setInputWindows(
2517 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2518 {ADISPLAY_ID_DEFAULT,
2519 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2520
2521 // Touch on second display.
2522 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2523 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2524 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2525
2526 // Window should receive motion event.
2527 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2528
2529 // Transfer touch focus
2530 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2531
2532 // The first window gets cancel.
2533 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2534 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2535
2536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2537 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2538 SECOND_DISPLAY_ID, {150, 50}))
2539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2540 firstWindowInPrimary->assertNoEvents();
2541 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2542
2543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2544 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2545 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2546 firstWindowInPrimary->assertNoEvents();
2547 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2548}
2549
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002550TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002552 sp<FakeWindowHandle> window =
2553 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2554
Vishnu Nair47074b82020-08-14 11:54:47 -07002555 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002557 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002558
2559 window->consumeFocusEvent(true);
2560
2561 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2562 mDispatcher->notifyKey(&keyArgs);
2563
2564 // Window should receive key down event.
2565 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2566}
2567
2568TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002570 sp<FakeWindowHandle> window =
2571 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2572
Arthur Hung72d8dc32020-03-28 00:48:39 +00002573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002574
2575 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2576 mDispatcher->notifyKey(&keyArgs);
2577 mDispatcher->waitForIdle();
2578
2579 window->assertNoEvents();
2580}
2581
2582// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2583TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002584 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002585 sp<FakeWindowHandle> window =
2586 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2587
Arthur Hung72d8dc32020-03-28 00:48:39 +00002588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002589
2590 // Send key
2591 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2592 mDispatcher->notifyKey(&keyArgs);
2593 // Send motion
2594 NotifyMotionArgs motionArgs =
2595 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2596 ADISPLAY_ID_DEFAULT);
2597 mDispatcher->notifyMotion(&motionArgs);
2598
2599 // Window should receive only the motion event
2600 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2601 window->assertNoEvents(); // Key event or focus event will not be received
2602}
2603
arthurhungea3f4fc2020-12-21 23:18:53 +08002604TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2606
2607 // Create first non touch modal window that supports split touch
2608 sp<FakeWindowHandle> firstWindow =
2609 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2610 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002611 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002612
2613 // Create second non touch modal window that supports split touch
2614 sp<FakeWindowHandle> secondWindow =
2615 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2616 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002617 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002618
2619 // Add the windows to the dispatcher
2620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2621
2622 PointF pointInFirst = {300, 200};
2623 PointF pointInSecond = {300, 600};
2624
2625 // Send down to the first window
2626 NotifyMotionArgs firstDownMotionArgs =
2627 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2628 ADISPLAY_ID_DEFAULT, {pointInFirst});
2629 mDispatcher->notifyMotion(&firstDownMotionArgs);
2630 // Only the first window should get the down event
2631 firstWindow->consumeMotionDown();
2632 secondWindow->assertNoEvents();
2633
2634 // Send down to the second window
2635 NotifyMotionArgs secondDownMotionArgs =
2636 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2637 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2638 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2639 {pointInFirst, pointInSecond});
2640 mDispatcher->notifyMotion(&secondDownMotionArgs);
2641 // The first window gets a move and the second a down
2642 firstWindow->consumeMotionMove();
2643 secondWindow->consumeMotionDown();
2644
2645 // Send pointer cancel to the second window
2646 NotifyMotionArgs pointerUpMotionArgs =
2647 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2648 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2649 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2650 {pointInFirst, pointInSecond});
2651 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2652 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2653 // The first window gets move and the second gets cancel.
2654 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2655 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2656
2657 // Send up event.
2658 NotifyMotionArgs upMotionArgs =
2659 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2660 ADISPLAY_ID_DEFAULT);
2661 mDispatcher->notifyMotion(&upMotionArgs);
2662 // The first window gets up and the second gets nothing.
2663 firstWindow->consumeMotionUp();
2664 secondWindow->assertNoEvents();
2665}
2666
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002667TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2669
2670 sp<FakeWindowHandle> window =
2671 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2673 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2674 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2675 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2676
2677 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2678 window->assertNoEvents();
2679 mDispatcher->waitForIdle();
2680}
2681
chaviwd1c23182019-12-20 18:44:56 -08002682class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002683public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002684 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002685 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002686 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002687 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002688 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002689 }
2690
chaviwd1c23182019-12-20 18:44:56 -08002691 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2692
2693 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2694 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2695 expectedDisplayId, expectedFlags);
2696 }
2697
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002698 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2699
2700 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2701
chaviwd1c23182019-12-20 18:44:56 -08002702 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2703 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2704 expectedDisplayId, expectedFlags);
2705 }
2706
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002707 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2708 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2709 expectedDisplayId, expectedFlags);
2710 }
2711
chaviwd1c23182019-12-20 18:44:56 -08002712 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2713 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2714 expectedDisplayId, expectedFlags);
2715 }
2716
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002717 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2718 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2719 expectedDisplayId, expectedFlags);
2720 }
2721
Evan Rosky84f07f02021-04-16 10:42:42 -07002722 MotionEvent* consumeMotion() {
2723 InputEvent* event = mInputReceiver->consume();
2724 if (!event) {
2725 ADD_FAILURE() << "No event was produced";
2726 return nullptr;
2727 }
2728 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2729 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2730 return nullptr;
2731 }
2732 return static_cast<MotionEvent*>(event);
2733 }
2734
chaviwd1c23182019-12-20 18:44:56 -08002735 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2736
2737private:
2738 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002739};
2740
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002741/**
2742 * Two entities that receive touch: A window, and a global monitor.
2743 * The touch goes to the window, and then the window disappears.
2744 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2745 * for the monitor, as well.
2746 * 1. foregroundWindow
2747 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2748 */
2749TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2751 sp<FakeWindowHandle> window =
2752 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2753
2754 FakeMonitorReceiver monitor =
2755 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2756 false /*isGestureMonitor*/);
2757
2758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2760 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2761 {100, 200}))
2762 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2763
2764 // Both the foreground window and the global monitor should receive the touch down
2765 window->consumeMotionDown();
2766 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2767
2768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2769 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2770 ADISPLAY_ID_DEFAULT, {110, 200}))
2771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2772
2773 window->consumeMotionMove();
2774 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2775
2776 // Now the foreground window goes away
2777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2778 window->consumeMotionCancel();
2779 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2780
2781 // If more events come in, there will be no more foreground window to send them to. This will
2782 // cause a cancel for the monitor, as well.
2783 ASSERT_EQ(InputEventInjectionResult::FAILED,
2784 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2785 ADISPLAY_ID_DEFAULT, {120, 200}))
2786 << "Injection should fail because the window was removed";
2787 window->assertNoEvents();
2788 // Global monitor now gets the cancel
2789 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2790}
2791
Michael Wright3a240c42019-12-10 20:53:41 +00002792// Tests for gesture monitors
2793TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002794 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002795 sp<FakeWindowHandle> window =
2796 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002798
chaviwd1c23182019-12-20 18:44:56 -08002799 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2800 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002801
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002803 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002804 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002805 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002806 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002807}
2808
2809TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002811 sp<FakeWindowHandle> window =
2812 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2813
2814 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002815 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002816
Arthur Hung72d8dc32020-03-28 00:48:39 +00002817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002818 setFocusedWindow(window);
2819
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002820 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002821
chaviwd1c23182019-12-20 18:44:56 -08002822 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2823 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002824
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002825 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2826 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002827 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002828 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002829}
2830
2831TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002832 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002833 sp<FakeWindowHandle> window =
2834 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002836
chaviwd1c23182019-12-20 18:44:56 -08002837 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2838 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002839
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002840 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002841 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002842 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002843 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002844 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002845
2846 window->releaseChannel();
2847
chaviwd1c23182019-12-20 18:44:56 -08002848 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002849
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002851 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002853 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002854}
2855
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002856TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2857 FakeMonitorReceiver monitor =
2858 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2859 true /*isGestureMonitor*/);
2860
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2863 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2864 ASSERT_TRUE(consumeSeq);
2865
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002866 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002867 monitor.finishEvent(*consumeSeq);
2868 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002869 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002870}
2871
Evan Rosky84f07f02021-04-16 10:42:42 -07002872// Tests for gesture monitors
2873TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2875 sp<FakeWindowHandle> window =
2876 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2878 window->setWindowOffset(20, 40);
2879 window->setWindowTransform(0, 1, -1, 0);
2880
2881 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2882 true /*isGestureMonitor*/);
2883
2884 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2885 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2886 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2887 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2888 MotionEvent* event = monitor.consumeMotion();
2889 // Even though window has transform, gesture monitor must not.
2890 ASSERT_EQ(ui::Transform(), event->getTransform());
2891}
2892
Arthur Hungb3307ee2021-10-14 10:57:37 +00002893TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2894 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2895 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2896 true /*isGestureMonitor*/);
2897
2898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2899 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2901 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2902}
2903
chaviw81e2bb92019-12-18 15:03:51 -08002904TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002905 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002906 sp<FakeWindowHandle> window =
2907 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2908
Arthur Hung72d8dc32020-03-28 00:48:39 +00002909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002910
2911 NotifyMotionArgs motionArgs =
2912 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2913 ADISPLAY_ID_DEFAULT);
2914
2915 mDispatcher->notifyMotion(&motionArgs);
2916 // Window should receive motion down event.
2917 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2918
2919 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002920 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002921 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2922 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2923 motionArgs.pointerCoords[0].getX() - 10);
2924
2925 mDispatcher->notifyMotion(&motionArgs);
2926 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2927 0 /*expectedFlags*/);
2928}
2929
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002930/**
2931 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2932 * the device default right away. In the test scenario, we check both the default value,
2933 * and the action of enabling / disabling.
2934 */
2935TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002936 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002937 sp<FakeWindowHandle> window =
2938 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2939
2940 // Set focused application.
2941 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002942 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002943
2944 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002945 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002946 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002947 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2948
2949 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002950 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002952 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2953
2954 SCOPED_TRACE("Disable touch mode");
2955 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002956 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002957 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002959 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002960 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2961
2962 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002963 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002964 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002965 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2966
2967 SCOPED_TRACE("Enable touch mode again");
2968 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00002969 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002970 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002972 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002973 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2974
2975 window->assertNoEvents();
2976}
2977
Gang Wange9087892020-01-07 12:17:14 -05002978TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002979 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002980 sp<FakeWindowHandle> window =
2981 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2982
2983 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002984 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002985
Arthur Hung72d8dc32020-03-28 00:48:39 +00002986 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002987 setFocusedWindow(window);
2988
Gang Wange9087892020-01-07 12:17:14 -05002989 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2990
2991 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2992 mDispatcher->notifyKey(&keyArgs);
2993
2994 InputEvent* event = window->consume();
2995 ASSERT_NE(event, nullptr);
2996
2997 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2998 ASSERT_NE(verified, nullptr);
2999 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3000
3001 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3002 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3003 ASSERT_EQ(keyArgs.source, verified->source);
3004 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3005
3006 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3007
3008 ASSERT_EQ(keyArgs.action, verifiedKey.action);
3009 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003010 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
3011 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3012 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3013 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3014 ASSERT_EQ(0, verifiedKey.repeatCount);
3015}
3016
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003017TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003019 sp<FakeWindowHandle> window =
3020 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3021
3022 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3023
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003024 ui::Transform transform;
3025 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3026
3027 gui::DisplayInfo displayInfo;
3028 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3029 displayInfo.transform = transform;
3030
3031 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003032
3033 NotifyMotionArgs motionArgs =
3034 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3035 ADISPLAY_ID_DEFAULT);
3036 mDispatcher->notifyMotion(&motionArgs);
3037
3038 InputEvent* event = window->consume();
3039 ASSERT_NE(event, nullptr);
3040
3041 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3042 ASSERT_NE(verified, nullptr);
3043 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3044
3045 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3046 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3047 EXPECT_EQ(motionArgs.source, verified->source);
3048 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3049
3050 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3051
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003052 const vec2 rawXY =
3053 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3054 motionArgs.pointerCoords[0].getXYValue());
3055 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3056 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003057 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3058 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3059 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3060 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3061 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3062}
3063
chaviw09c8d2d2020-08-24 15:48:26 -07003064/**
3065 * Ensure that separate calls to sign the same data are generating the same key.
3066 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3067 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3068 * tests.
3069 */
3070TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3071 KeyEvent event = getTestKeyEvent();
3072 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3073
3074 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3075 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3076 ASSERT_EQ(hmac1, hmac2);
3077}
3078
3079/**
3080 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3081 */
3082TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3083 KeyEvent event = getTestKeyEvent();
3084 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3085 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3086
3087 verifiedEvent.deviceId += 1;
3088 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3089
3090 verifiedEvent.source += 1;
3091 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3092
3093 verifiedEvent.eventTimeNanos += 1;
3094 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3095
3096 verifiedEvent.displayId += 1;
3097 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3098
3099 verifiedEvent.action += 1;
3100 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3101
3102 verifiedEvent.downTimeNanos += 1;
3103 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3104
3105 verifiedEvent.flags += 1;
3106 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3107
3108 verifiedEvent.keyCode += 1;
3109 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3110
3111 verifiedEvent.scanCode += 1;
3112 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3113
3114 verifiedEvent.metaState += 1;
3115 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3116
3117 verifiedEvent.repeatCount += 1;
3118 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3119}
3120
Vishnu Nair958da932020-08-21 17:12:37 -07003121TEST_F(InputDispatcherTest, SetFocusedWindow) {
3122 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3123 sp<FakeWindowHandle> windowTop =
3124 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3125 sp<FakeWindowHandle> windowSecond =
3126 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3127 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3128
3129 // Top window is also focusable but is not granted focus.
3130 windowTop->setFocusable(true);
3131 windowSecond->setFocusable(true);
3132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3133 setFocusedWindow(windowSecond);
3134
3135 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3137 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003138
3139 // Focused window should receive event.
3140 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3141 windowTop->assertNoEvents();
3142}
3143
3144TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3145 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3146 sp<FakeWindowHandle> window =
3147 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3148 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3149
3150 window->setFocusable(true);
3151 // Release channel for window is no longer valid.
3152 window->releaseChannel();
3153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3154 setFocusedWindow(window);
3155
3156 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003157 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3158 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003159
3160 // window channel is invalid, so it should not receive any input event.
3161 window->assertNoEvents();
3162}
3163
3164TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3165 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3166 sp<FakeWindowHandle> window =
3167 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3168 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3169
3170 // Window is not focusable.
3171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3172 setFocusedWindow(window);
3173
3174 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003175 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3176 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003177
3178 // window is invalid, so it should not receive any input event.
3179 window->assertNoEvents();
3180}
3181
3182TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3183 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3184 sp<FakeWindowHandle> windowTop =
3185 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3186 sp<FakeWindowHandle> windowSecond =
3187 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3188 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3189
3190 windowTop->setFocusable(true);
3191 windowSecond->setFocusable(true);
3192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3193 setFocusedWindow(windowTop);
3194 windowTop->consumeFocusEvent(true);
3195
3196 setFocusedWindow(windowSecond, windowTop);
3197 windowSecond->consumeFocusEvent(true);
3198 windowTop->consumeFocusEvent(false);
3199
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3201 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003202
3203 // Focused window should receive event.
3204 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3205}
3206
3207TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3208 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3209 sp<FakeWindowHandle> windowTop =
3210 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3211 sp<FakeWindowHandle> windowSecond =
3212 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3213 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3214
3215 windowTop->setFocusable(true);
3216 windowSecond->setFocusable(true);
3217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3218 setFocusedWindow(windowSecond, windowTop);
3219
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003220 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3221 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003222
3223 // Event should be dropped.
3224 windowTop->assertNoEvents();
3225 windowSecond->assertNoEvents();
3226}
3227
3228TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3229 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3230 sp<FakeWindowHandle> window =
3231 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3232 sp<FakeWindowHandle> previousFocusedWindow =
3233 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3234 ADISPLAY_ID_DEFAULT);
3235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3236
3237 window->setFocusable(true);
3238 previousFocusedWindow->setFocusable(true);
3239 window->setVisible(false);
3240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3241 setFocusedWindow(previousFocusedWindow);
3242 previousFocusedWindow->consumeFocusEvent(true);
3243
3244 // Requesting focus on invisible window takes focus from currently focused window.
3245 setFocusedWindow(window);
3246 previousFocusedWindow->consumeFocusEvent(false);
3247
3248 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003250 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003251 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003252
3253 // Window does not get focus event or key down.
3254 window->assertNoEvents();
3255
3256 // Window becomes visible.
3257 window->setVisible(true);
3258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3259
3260 // Window receives focus event.
3261 window->consumeFocusEvent(true);
3262 // Focused window receives key down.
3263 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3264}
3265
Vishnu Nair599f1412021-06-21 10:39:58 -07003266TEST_F(InputDispatcherTest, DisplayRemoved) {
3267 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3268 sp<FakeWindowHandle> window =
3269 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3270 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3271
3272 // window is granted focus.
3273 window->setFocusable(true);
3274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3275 setFocusedWindow(window);
3276 window->consumeFocusEvent(true);
3277
3278 // When a display is removed window loses focus.
3279 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3280 window->consumeFocusEvent(false);
3281}
3282
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003283/**
3284 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3285 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3286 * of the 'slipperyEnterWindow'.
3287 *
3288 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3289 * a way so that the touched location is no longer covered by the top window.
3290 *
3291 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3292 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3293 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3294 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3295 * with ACTION_DOWN).
3296 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3297 * window moved itself away from the touched location and had Flag::SLIPPERY.
3298 *
3299 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3300 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3301 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3302 *
3303 * In this test, we ensure that the event received by the bottom window has
3304 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3305 */
3306TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3307 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3308 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3309
3310 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3311 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3312
3313 sp<FakeWindowHandle> slipperyExitWindow =
3314 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003315 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003316 // Make sure this one overlaps the bottom window
3317 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3318 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3319 // one. Windows with the same owner are not considered to be occluding each other.
3320 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3321
3322 sp<FakeWindowHandle> slipperyEnterWindow =
3323 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3324 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3325
3326 mDispatcher->setInputWindows(
3327 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3328
3329 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3330 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3331 ADISPLAY_ID_DEFAULT, {{50, 50}});
3332 mDispatcher->notifyMotion(&args);
3333 slipperyExitWindow->consumeMotionDown();
3334 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3335 mDispatcher->setInputWindows(
3336 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3337
3338 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3339 ADISPLAY_ID_DEFAULT, {{51, 51}});
3340 mDispatcher->notifyMotion(&args);
3341
3342 slipperyExitWindow->consumeMotionCancel();
3343
3344 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3345 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3346}
3347
Garfield Tan1c7bc862020-01-28 13:24:04 -08003348class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3349protected:
3350 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3351 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3352
Chris Yea209fde2020-07-22 13:54:51 -07003353 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003354 sp<FakeWindowHandle> mWindow;
3355
3356 virtual void SetUp() override {
3357 mFakePolicy = new FakeInputDispatcherPolicy();
3358 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003359 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003360 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3361 ASSERT_EQ(OK, mDispatcher->start());
3362
3363 setUpWindow();
3364 }
3365
3366 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003367 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003368 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3369
Vishnu Nair47074b82020-08-14 11:54:47 -07003370 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003372 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003373 mWindow->consumeFocusEvent(true);
3374 }
3375
Chris Ye2ad95392020-09-01 13:44:44 -07003376 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003377 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003378 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003379 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3380 mDispatcher->notifyKey(&keyArgs);
3381
3382 // Window should receive key down event.
3383 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3384 }
3385
3386 void expectKeyRepeatOnce(int32_t repeatCount) {
3387 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3388 InputEvent* repeatEvent = mWindow->consume();
3389 ASSERT_NE(nullptr, repeatEvent);
3390
3391 uint32_t eventType = repeatEvent->getType();
3392 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3393
3394 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3395 uint32_t eventAction = repeatKeyEvent->getAction();
3396 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3397 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3398 }
3399
Chris Ye2ad95392020-09-01 13:44:44 -07003400 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003401 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003402 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003403 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3404 mDispatcher->notifyKey(&keyArgs);
3405
3406 // Window should receive key down event.
3407 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3408 0 /*expectedFlags*/);
3409 }
3410};
3411
3412TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003413 sendAndConsumeKeyDown(1 /* deviceId */);
3414 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3415 expectKeyRepeatOnce(repeatCount);
3416 }
3417}
3418
3419TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3420 sendAndConsumeKeyDown(1 /* deviceId */);
3421 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3422 expectKeyRepeatOnce(repeatCount);
3423 }
3424 sendAndConsumeKeyDown(2 /* deviceId */);
3425 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003426 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3427 expectKeyRepeatOnce(repeatCount);
3428 }
3429}
3430
3431TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003432 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003433 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003434 sendAndConsumeKeyUp(1 /* deviceId */);
3435 mWindow->assertNoEvents();
3436}
3437
3438TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3439 sendAndConsumeKeyDown(1 /* deviceId */);
3440 expectKeyRepeatOnce(1 /*repeatCount*/);
3441 sendAndConsumeKeyDown(2 /* deviceId */);
3442 expectKeyRepeatOnce(1 /*repeatCount*/);
3443 // Stale key up from device 1.
3444 sendAndConsumeKeyUp(1 /* deviceId */);
3445 // Device 2 is still down, keep repeating
3446 expectKeyRepeatOnce(2 /*repeatCount*/);
3447 expectKeyRepeatOnce(3 /*repeatCount*/);
3448 // Device 2 key up
3449 sendAndConsumeKeyUp(2 /* deviceId */);
3450 mWindow->assertNoEvents();
3451}
3452
3453TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3454 sendAndConsumeKeyDown(1 /* deviceId */);
3455 expectKeyRepeatOnce(1 /*repeatCount*/);
3456 sendAndConsumeKeyDown(2 /* deviceId */);
3457 expectKeyRepeatOnce(1 /*repeatCount*/);
3458 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3459 sendAndConsumeKeyUp(2 /* deviceId */);
3460 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003461 mWindow->assertNoEvents();
3462}
3463
liushenxiang42232912021-05-21 20:24:09 +08003464TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3465 sendAndConsumeKeyDown(DEVICE_ID);
3466 expectKeyRepeatOnce(1 /*repeatCount*/);
3467 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3468 mDispatcher->notifyDeviceReset(&args);
3469 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3470 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3471 mWindow->assertNoEvents();
3472}
3473
Garfield Tan1c7bc862020-01-28 13:24:04 -08003474TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003475 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003476 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3477 InputEvent* repeatEvent = mWindow->consume();
3478 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3479 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3480 IdGenerator::getSource(repeatEvent->getId()));
3481 }
3482}
3483
3484TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003485 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003486
3487 std::unordered_set<int32_t> idSet;
3488 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3489 InputEvent* repeatEvent = mWindow->consume();
3490 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3491 int32_t id = repeatEvent->getId();
3492 EXPECT_EQ(idSet.end(), idSet.find(id));
3493 idSet.insert(id);
3494 }
3495}
3496
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003497/* Test InputDispatcher for MultiDisplay */
3498class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3499public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003500 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003501 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003502
Chris Yea209fde2020-07-22 13:54:51 -07003503 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003504 windowInPrimary =
3505 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003506
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003507 // Set focus window for primary display, but focused display would be second one.
3508 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003509 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003511 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003512 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003513
Chris Yea209fde2020-07-22 13:54:51 -07003514 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003515 windowInSecondary =
3516 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003517 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003518 // Set focus display to second one.
3519 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3520 // Set focus window for second display.
3521 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003522 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003523 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003524 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003525 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003526 }
3527
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003528 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003529 InputDispatcherTest::TearDown();
3530
Chris Yea209fde2020-07-22 13:54:51 -07003531 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003532 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003533 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003534 windowInSecondary.clear();
3535 }
3536
3537protected:
Chris Yea209fde2020-07-22 13:54:51 -07003538 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003539 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003540 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003541 sp<FakeWindowHandle> windowInSecondary;
3542};
3543
3544TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3545 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3548 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003549 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003550 windowInSecondary->assertNoEvents();
3551
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003552 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003556 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003557 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003558}
3559
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003560TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003561 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3563 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003564 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003565 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003566 windowInSecondary->assertNoEvents();
3567
3568 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003570 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003571 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003572 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003573
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003574 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003575 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003576
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003577 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003578 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3579 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003580
3581 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003582 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003583 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003584 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003585 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003586 windowInSecondary->assertNoEvents();
3587}
3588
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003589// Test per-display input monitors for motion event.
3590TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003591 FakeMonitorReceiver monitorInPrimary =
3592 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3593 FakeMonitorReceiver monitorInSecondary =
3594 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595
3596 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003600 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003601 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003602 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003603 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003604
3605 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003609 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003610 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003611 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003612 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003613
3614 // Test inject a non-pointer motion event.
3615 // If specific a display, it will dispatch to the focused window of particular display,
3616 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003620 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003621 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003622 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003623 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003624}
3625
3626// Test per-display input monitors for key event.
3627TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003628 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003629 FakeMonitorReceiver monitorInPrimary =
3630 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3631 FakeMonitorReceiver monitorInSecondary =
3632 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003633
3634 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3636 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003637 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003638 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003639 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003640 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003641}
3642
Vishnu Nair958da932020-08-21 17:12:37 -07003643TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3644 sp<FakeWindowHandle> secondWindowInPrimary =
3645 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3646 secondWindowInPrimary->setFocusable(true);
3647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3648 setFocusedWindow(secondWindowInPrimary);
3649 windowInPrimary->consumeFocusEvent(false);
3650 secondWindowInPrimary->consumeFocusEvent(true);
3651
3652 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3654 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003655 windowInPrimary->assertNoEvents();
3656 windowInSecondary->assertNoEvents();
3657 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3658}
3659
Jackal Guof9696682018-10-05 12:23:23 +08003660class InputFilterTest : public InputDispatcherTest {
3661protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003662 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3663 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003664 NotifyMotionArgs motionArgs;
3665
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003666 motionArgs =
3667 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003668 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003669 motionArgs =
3670 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003671 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003672 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003673 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003674 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3675 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003676 } else {
3677 mFakePolicy->assertFilterInputEventWasNotCalled();
3678 }
3679 }
3680
3681 void testNotifyKey(bool expectToBeFiltered) {
3682 NotifyKeyArgs keyArgs;
3683
3684 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3685 mDispatcher->notifyKey(&keyArgs);
3686 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3687 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003688 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003689
3690 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003691 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003692 } else {
3693 mFakePolicy->assertFilterInputEventWasNotCalled();
3694 }
3695 }
3696};
3697
3698// Test InputFilter for MotionEvent
3699TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3700 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3701 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3702 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3703
3704 // Enable InputFilter
3705 mDispatcher->setInputFilterEnabled(true);
3706 // Test touch on both primary and second display, and check if both events are filtered.
3707 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3708 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3709
3710 // Disable InputFilter
3711 mDispatcher->setInputFilterEnabled(false);
3712 // Test touch on both primary and second display, and check if both events aren't filtered.
3713 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3714 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3715}
3716
3717// Test InputFilter for KeyEvent
3718TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3719 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3720 testNotifyKey(/*expectToBeFiltered*/ false);
3721
3722 // Enable InputFilter
3723 mDispatcher->setInputFilterEnabled(true);
3724 // Send a key event, and check if it is filtered.
3725 testNotifyKey(/*expectToBeFiltered*/ true);
3726
3727 // Disable InputFilter
3728 mDispatcher->setInputFilterEnabled(false);
3729 // Send a key event, and check if it isn't filtered.
3730 testNotifyKey(/*expectToBeFiltered*/ false);
3731}
3732
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003733// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3734// logical display coordinate space.
3735TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3736 ui::Transform firstDisplayTransform;
3737 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3738 ui::Transform secondDisplayTransform;
3739 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3740
3741 std::vector<gui::DisplayInfo> displayInfos(2);
3742 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3743 displayInfos[0].transform = firstDisplayTransform;
3744 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3745 displayInfos[1].transform = secondDisplayTransform;
3746
3747 mDispatcher->onWindowInfosChanged({}, displayInfos);
3748
3749 // Enable InputFilter
3750 mDispatcher->setInputFilterEnabled(true);
3751
3752 // Ensure the correct transforms are used for the displays.
3753 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3754 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3755}
3756
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003757class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3758protected:
3759 virtual void SetUp() override {
3760 InputDispatcherTest::SetUp();
3761
3762 /**
3763 * We don't need to enable input filter to test the injected event policy, but we enabled it
3764 * here to make the tests more realistic, since this policy only matters when inputfilter is
3765 * on.
3766 */
3767 mDispatcher->setInputFilterEnabled(true);
3768
3769 std::shared_ptr<InputApplicationHandle> application =
3770 std::make_shared<FakeApplicationHandle>();
3771 mWindow =
3772 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3773
3774 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3775 mWindow->setFocusable(true);
3776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3777 setFocusedWindow(mWindow);
3778 mWindow->consumeFocusEvent(true);
3779 }
3780
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003781 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3782 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003783 KeyEvent event;
3784
3785 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3786 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3787 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3788 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3789 const int32_t additionalPolicyFlags =
3790 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3792 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3793 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3794 policyFlags | additionalPolicyFlags));
3795
3796 InputEvent* received = mWindow->consume();
3797 ASSERT_NE(nullptr, received);
3798 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003799 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3800 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3801 ASSERT_EQ(flags, keyEvent.getFlags());
3802 }
3803
3804 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3805 int32_t flags) {
3806 MotionEvent event;
3807 PointerProperties pointerProperties[1];
3808 PointerCoords pointerCoords[1];
3809 pointerProperties[0].clear();
3810 pointerProperties[0].id = 0;
3811 pointerCoords[0].clear();
3812 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3813 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3814
3815 ui::Transform identityTransform;
3816 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3817 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3818 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3819 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3820 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003821 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003822 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003823 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3824
3825 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3827 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3828 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3829 policyFlags | additionalPolicyFlags));
3830
3831 InputEvent* received = mWindow->consume();
3832 ASSERT_NE(nullptr, received);
3833 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3834 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3835 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3836 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003837 }
3838
3839private:
3840 sp<FakeWindowHandle> mWindow;
3841};
3842
3843TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003844 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3845 // filter. Without it, the event will no different from a regularly injected event, and the
3846 // injected device id will be overwritten.
3847 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3848 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003849}
3850
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003851TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003852 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003853 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3854 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3855}
3856
3857TEST_F(InputFilterInjectionPolicyTest,
3858 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3859 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3860 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3861 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003862}
3863
3864TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3865 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003866 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003867}
3868
chaviwfd6d3512019-03-25 13:23:49 -07003869class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003870 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003871 InputDispatcherTest::SetUp();
3872
Chris Yea209fde2020-07-22 13:54:51 -07003873 std::shared_ptr<FakeApplicationHandle> application =
3874 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003875 mUnfocusedWindow =
3876 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003877 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3878 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3879 // window.
chaviw3277faf2021-05-19 16:45:23 -05003880 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003881
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003882 mFocusedWindow =
3883 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3884 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003885 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003886
3887 // Set focused application.
3888 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003889 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003890
3891 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003893 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003894 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003895 }
3896
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003897 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003898 InputDispatcherTest::TearDown();
3899
3900 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003901 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003902 }
3903
3904protected:
3905 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003906 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003907 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003908};
3909
3910// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3911// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3912// the onPointerDownOutsideFocus callback.
3913TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003915 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3916 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003918 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003919
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003920 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003921 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3922}
3923
3924// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3925// DOWN on the window that doesn't have focus. Ensure no window received the
3926// onPointerDownOutsideFocus callback.
3927TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003929 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003931 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003932
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003933 ASSERT_TRUE(mDispatcher->waitForIdle());
3934 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003935}
3936
3937// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3938// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3939TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3941 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003942 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003943 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003944
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003945 ASSERT_TRUE(mDispatcher->waitForIdle());
3946 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003947}
3948
3949// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3950// DOWN on the window that already has focus. Ensure no window received the
3951// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003952TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003954 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003955 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003956 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003957 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003958
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003959 ASSERT_TRUE(mDispatcher->waitForIdle());
3960 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003961}
3962
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003963// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3964// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3965TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3966 const MotionEvent event =
3967 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3968 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3969 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3970 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3971 .build();
3972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3973 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3974 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3975
3976 ASSERT_TRUE(mDispatcher->waitForIdle());
3977 mFakePolicy->assertOnPointerDownWasNotCalled();
3978 // Ensure that the unfocused window did not receive any FOCUS events.
3979 mUnfocusedWindow->assertNoEvents();
3980}
3981
chaviwaf87b3e2019-10-01 16:59:28 -07003982// These tests ensures we can send touch events to a single client when there are multiple input
3983// windows that point to the same client token.
3984class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3985 virtual void SetUp() override {
3986 InputDispatcherTest::SetUp();
3987
Chris Yea209fde2020-07-22 13:54:51 -07003988 std::shared_ptr<FakeApplicationHandle> application =
3989 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003990 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3991 ADISPLAY_ID_DEFAULT);
3992 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3993 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003994 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003995 mWindow1->setFrame(Rect(0, 0, 100, 100));
3996
3997 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3998 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003999 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004000 mWindow2->setFrame(Rect(100, 100, 200, 200));
4001
Arthur Hung72d8dc32020-03-28 00:48:39 +00004002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004003 }
4004
4005protected:
4006 sp<FakeWindowHandle> mWindow1;
4007 sp<FakeWindowHandle> mWindow2;
4008
4009 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004010 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004011 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4012 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004013 }
4014
4015 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4016 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004017 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004018 InputEvent* event = window->consume();
4019
4020 ASSERT_NE(nullptr, event) << name.c_str()
4021 << ": consumer should have returned non-NULL event.";
4022
4023 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4024 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4025 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4026
4027 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004028 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004029
4030 for (size_t i = 0; i < points.size(); i++) {
4031 float expectedX = points[i].x;
4032 float expectedY = points[i].y;
4033
4034 EXPECT_EQ(expectedX, motionEvent.getX(i))
4035 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4036 << ", got " << motionEvent.getX(i);
4037 EXPECT_EQ(expectedY, motionEvent.getY(i))
4038 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4039 << ", got " << motionEvent.getY(i);
4040 }
4041 }
chaviw9eaa22c2020-07-01 16:21:27 -07004042
4043 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4044 std::vector<PointF> expectedPoints) {
4045 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4046 ADISPLAY_ID_DEFAULT, touchedPoints);
4047 mDispatcher->notifyMotion(&motionArgs);
4048
4049 // Always consume from window1 since it's the window that has the InputReceiver
4050 consumeMotionEvent(mWindow1, action, expectedPoints);
4051 }
chaviwaf87b3e2019-10-01 16:59:28 -07004052};
4053
4054TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4055 // Touch Window 1
4056 PointF touchedPoint = {10, 10};
4057 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004058 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004059
4060 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004061 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004062
4063 // Touch Window 2
4064 touchedPoint = {150, 150};
4065 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004066 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004067}
4068
chaviw9eaa22c2020-07-01 16:21:27 -07004069TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4070 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004071 mWindow2->setWindowScale(0.5f, 0.5f);
4072
4073 // Touch Window 1
4074 PointF touchedPoint = {10, 10};
4075 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004076 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004077 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004078 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004079
4080 // Touch Window 2
4081 touchedPoint = {150, 150};
4082 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004083 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4084 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004085
chaviw9eaa22c2020-07-01 16:21:27 -07004086 // Update the transform so rotation is set
4087 mWindow2->setWindowTransform(0, -1, 1, 0);
4088 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4089 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004090}
4091
chaviw9eaa22c2020-07-01 16:21:27 -07004092TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004093 mWindow2->setWindowScale(0.5f, 0.5f);
4094
4095 // Touch Window 1
4096 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4097 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004098 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004099
4100 // Touch Window 2
4101 int32_t actionPointerDown =
4102 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004103 touchedPoints.push_back(PointF{150, 150});
4104 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4105 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004106
chaviw9eaa22c2020-07-01 16:21:27 -07004107 // Release Window 2
4108 int32_t actionPointerUp =
4109 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4110 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4111 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004112
chaviw9eaa22c2020-07-01 16:21:27 -07004113 // Update the transform so rotation is set for Window 2
4114 mWindow2->setWindowTransform(0, -1, 1, 0);
4115 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4116 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004117}
4118
chaviw9eaa22c2020-07-01 16:21:27 -07004119TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004120 mWindow2->setWindowScale(0.5f, 0.5f);
4121
4122 // Touch Window 1
4123 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4124 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004125 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004126
4127 // Touch Window 2
4128 int32_t actionPointerDown =
4129 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004130 touchedPoints.push_back(PointF{150, 150});
4131 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004132
chaviw9eaa22c2020-07-01 16:21:27 -07004133 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004134
4135 // Move both windows
4136 touchedPoints = {{20, 20}, {175, 175}};
4137 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4138 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4139
chaviw9eaa22c2020-07-01 16:21:27 -07004140 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004141
chaviw9eaa22c2020-07-01 16:21:27 -07004142 // Release Window 2
4143 int32_t actionPointerUp =
4144 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4145 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4146 expectedPoints.pop_back();
4147
4148 // Touch Window 2
4149 mWindow2->setWindowTransform(0, -1, 1, 0);
4150 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4151 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4152
4153 // Move both windows
4154 touchedPoints = {{20, 20}, {175, 175}};
4155 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4156 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4157
4158 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004159}
4160
4161TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4162 mWindow1->setWindowScale(0.5f, 0.5f);
4163
4164 // Touch Window 1
4165 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4166 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004167 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004168
4169 // Touch Window 2
4170 int32_t actionPointerDown =
4171 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004172 touchedPoints.push_back(PointF{150, 150});
4173 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004174
chaviw9eaa22c2020-07-01 16:21:27 -07004175 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004176
4177 // Move both windows
4178 touchedPoints = {{20, 20}, {175, 175}};
4179 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4180 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4181
chaviw9eaa22c2020-07-01 16:21:27 -07004182 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004183}
4184
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004185class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4186 virtual void SetUp() override {
4187 InputDispatcherTest::SetUp();
4188
Chris Yea209fde2020-07-22 13:54:51 -07004189 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004190 mApplication->setDispatchingTimeout(20ms);
4191 mWindow =
4192 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4193 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004194 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004195 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004196 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4197 // window.
chaviw3277faf2021-05-19 16:45:23 -05004198 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004199
4200 // Set focused application.
4201 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4202
4203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004204 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004205 mWindow->consumeFocusEvent(true);
4206 }
4207
4208 virtual void TearDown() override {
4209 InputDispatcherTest::TearDown();
4210 mWindow.clear();
4211 }
4212
4213protected:
Chris Yea209fde2020-07-22 13:54:51 -07004214 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004215 sp<FakeWindowHandle> mWindow;
4216 static constexpr PointF WINDOW_LOCATION = {20, 20};
4217
4218 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004220 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4221 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004223 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4224 WINDOW_LOCATION));
4225 }
4226};
4227
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004228// Send a tap and respond, which should not cause an ANR.
4229TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4230 tapOnWindow();
4231 mWindow->consumeMotionDown();
4232 mWindow->consumeMotionUp();
4233 ASSERT_TRUE(mDispatcher->waitForIdle());
4234 mFakePolicy->assertNotifyAnrWasNotCalled();
4235}
4236
4237// Send a regular key and respond, which should not cause an ANR.
4238TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004240 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4241 ASSERT_TRUE(mDispatcher->waitForIdle());
4242 mFakePolicy->assertNotifyAnrWasNotCalled();
4243}
4244
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004245TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4246 mWindow->setFocusable(false);
4247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4248 mWindow->consumeFocusEvent(false);
4249
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004250 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004251 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004252 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4253 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004255 // Key will not go to window because we have no focused window.
4256 // The 'no focused window' ANR timer should start instead.
4257
4258 // Now, the focused application goes away.
4259 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4260 // The key should get dropped and there should be no ANR.
4261
4262 ASSERT_TRUE(mDispatcher->waitForIdle());
4263 mFakePolicy->assertNotifyAnrWasNotCalled();
4264}
4265
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004266// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004267// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4268// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004269TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004271 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4272 WINDOW_LOCATION));
4273
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004274 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4275 ASSERT_TRUE(sequenceNum);
4276 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004277 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004278
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004279 mWindow->finishEvent(*sequenceNum);
4280 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4281 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004282 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004283 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004284}
4285
4286// Send a key to the app and have the app not respond right away.
4287TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4288 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004290 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4291 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004293 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004294 ASSERT_TRUE(mDispatcher->waitForIdle());
4295}
4296
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004297// We have a focused application, but no focused window
4298TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004299 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4301 mWindow->consumeFocusEvent(false);
4302
4303 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004305 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4306 WINDOW_LOCATION));
4307 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4308 mDispatcher->waitForIdle();
4309 mFakePolicy->assertNotifyAnrWasNotCalled();
4310
4311 // Once a focused event arrives, we get an ANR for this application
4312 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4313 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004314 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004315 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004316 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004317 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004318 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004319 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004320 ASSERT_TRUE(mDispatcher->waitForIdle());
4321}
4322
4323// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004324// Make sure that we don't notify policy twice about the same ANR.
4325TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004326 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4328 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004329
4330 // Once a focused event arrives, we get an ANR for this application
4331 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4332 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004333 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004334 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004335 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004336 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004337 const std::chrono::duration appTimeout =
4338 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004339 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004340
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004341 std::this_thread::sleep_for(appTimeout);
4342 // ANR should not be raised again. It is up to policy to do that if it desires.
4343 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004345 // If we now get a focused window, the ANR should stop, but the policy handles that via
4346 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004347 ASSERT_TRUE(mDispatcher->waitForIdle());
4348}
4349
4350// We have a focused application, but no focused window
4351TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004352 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4354 mWindow->consumeFocusEvent(false);
4355
4356 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004357 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004358 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4360 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361
4362 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004363 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004364
4365 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004366 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004367 ASSERT_TRUE(mDispatcher->waitForIdle());
4368 mWindow->assertNoEvents();
4369}
4370
4371/**
4372 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4373 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4374 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4375 * the ANR mechanism should still work.
4376 *
4377 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4378 * DOWN event, while not responding on the second one.
4379 */
4380TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4381 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4382 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4383 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4384 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4385 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004386 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387
4388 // Now send ACTION_UP, with identical timestamp
4389 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4390 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4391 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4392 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394
4395 // We have now sent down and up. Let's consume first event and then ANR on the second.
4396 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4397 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004398 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004399}
4400
4401// If an app is not responding to a key event, gesture monitors should continue to receive
4402// new motion events
4403TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4404 FakeMonitorReceiver monitor =
4405 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4406 true /*isGestureMonitor*/);
4407
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4409 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004410 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412
4413 // Stuck on the ACTION_UP
4414 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004415 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004416
4417 // New tap will go to the gesture monitor, but not to the window
4418 tapOnWindow();
4419 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4420 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4421
4422 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4423 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004424 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004425 mWindow->assertNoEvents();
4426 monitor.assertNoEvents();
4427}
4428
4429// If an app is not responding to a motion event, gesture monitors should continue to receive
4430// new motion events
4431TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4432 FakeMonitorReceiver monitor =
4433 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4434 true /*isGestureMonitor*/);
4435
4436 tapOnWindow();
4437 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4438 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4439
4440 mWindow->consumeMotionDown();
4441 // Stuck on the ACTION_UP
4442 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004443 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444
4445 // New tap will go to the gesture monitor, but not to the window
4446 tapOnWindow();
4447 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4448 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4449
4450 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4451 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004452 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004453 mWindow->assertNoEvents();
4454 monitor.assertNoEvents();
4455}
4456
4457// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4458// process events, you don't get an anr. When the window later becomes unresponsive again, you
4459// get an ANR again.
4460// 1. tap -> block on ACTION_UP -> receive ANR
4461// 2. consume all pending events (= queue becomes healthy again)
4462// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4463TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4464 tapOnWindow();
4465
4466 mWindow->consumeMotionDown();
4467 // Block on ACTION_UP
4468 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004469 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004470 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4471 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004472 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 mWindow->assertNoEvents();
4474
4475 tapOnWindow();
4476 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004477 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004478 mWindow->consumeMotionUp();
4479
4480 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004481 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004482 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483 mWindow->assertNoEvents();
4484}
4485
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004486// If a connection remains unresponsive for a while, make sure policy is only notified once about
4487// it.
4488TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004490 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4491 WINDOW_LOCATION));
4492
4493 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004494 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004496 // 'notifyConnectionUnresponsive' should only be called once per connection
4497 mFakePolicy->assertNotifyAnrWasNotCalled();
4498 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 mWindow->consumeMotionDown();
4500 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4501 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4502 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004503 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004504 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004505 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004506}
4507
4508/**
4509 * If a window is processing a motion event, and then a key event comes in, the key event should
4510 * not to to the focused window until the motion is processed.
4511 *
4512 * Warning!!!
4513 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4514 * and the injection timeout that we specify when injecting the key.
4515 * We must have the injection timeout (10ms) be smaller than
4516 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4517 *
4518 * If that value changes, this test should also change.
4519 */
4520TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4521 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4522 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4523
4524 tapOnWindow();
4525 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4526 ASSERT_TRUE(downSequenceNum);
4527 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4528 ASSERT_TRUE(upSequenceNum);
4529 // Don't finish the events yet, and send a key
4530 // Injection will "succeed" because we will eventually give up and send the key to the focused
4531 // window even if motions are still being processed. But because the injection timeout is short,
4532 // we will receive INJECTION_TIMED_OUT as the result.
4533
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004534 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4537 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538 // Key will not be sent to the window, yet, because the window is still processing events
4539 // and the key remains pending, waiting for the touch events to be processed
4540 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4541 ASSERT_FALSE(keySequenceNum);
4542
4543 std::this_thread::sleep_for(500ms);
4544 // if we wait long enough though, dispatcher will give up, and still send the key
4545 // to the focused window, even though we have not yet finished the motion event
4546 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4547 mWindow->finishEvent(*downSequenceNum);
4548 mWindow->finishEvent(*upSequenceNum);
4549}
4550
4551/**
4552 * If a window is processing a motion event, and then a key event comes in, the key event should
4553 * not go to the focused window until the motion is processed.
4554 * If then a new motion comes in, then the pending key event should be going to the currently
4555 * focused window right away.
4556 */
4557TEST_F(InputDispatcherSingleWindowAnr,
4558 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4559 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4561
4562 tapOnWindow();
4563 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4564 ASSERT_TRUE(downSequenceNum);
4565 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4566 ASSERT_TRUE(upSequenceNum);
4567 // Don't finish the events yet, and send a key
4568 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004570 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004571 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004572 // At this point, key is still pending, and should not be sent to the application yet.
4573 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4574 ASSERT_FALSE(keySequenceNum);
4575
4576 // Now tap down again. It should cause the pending key to go to the focused window right away.
4577 tapOnWindow();
4578 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4579 // the other events yet. We can finish events in any order.
4580 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4581 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4582 mWindow->consumeMotionDown();
4583 mWindow->consumeMotionUp();
4584 mWindow->assertNoEvents();
4585}
4586
4587class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4588 virtual void SetUp() override {
4589 InputDispatcherTest::SetUp();
4590
Chris Yea209fde2020-07-22 13:54:51 -07004591 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592 mApplication->setDispatchingTimeout(10ms);
4593 mUnfocusedWindow =
4594 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4595 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4596 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4597 // window.
4598 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004599 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4600 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4601 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004602
4603 mFocusedWindow =
4604 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004605 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004607 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608
4609 // Set focused application.
4610 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004611 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612
4613 // Expect one focus window exist in display.
4614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004615 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 mFocusedWindow->consumeFocusEvent(true);
4617 }
4618
4619 virtual void TearDown() override {
4620 InputDispatcherTest::TearDown();
4621
4622 mUnfocusedWindow.clear();
4623 mFocusedWindow.clear();
4624 }
4625
4626protected:
Chris Yea209fde2020-07-22 13:54:51 -07004627 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 sp<FakeWindowHandle> mUnfocusedWindow;
4629 sp<FakeWindowHandle> mFocusedWindow;
4630 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4631 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4632 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4633
4634 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4635
4636 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4637
4638private:
4639 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4642 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4645 location));
4646 }
4647};
4648
4649// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4650// should be ANR'd first.
4651TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4654 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004656 mFocusedWindow->consumeMotionDown();
4657 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4658 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4659 // We consumed all events, so no ANR
4660 ASSERT_TRUE(mDispatcher->waitForIdle());
4661 mFakePolicy->assertNotifyAnrWasNotCalled();
4662
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4665 FOCUSED_WINDOW_LOCATION));
4666 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4667 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668
4669 const std::chrono::duration timeout =
4670 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004671 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004672 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4673 // sequence to make it consistent
4674 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004676 mFocusedWindow->consumeMotionDown();
4677 // This cancel is generated because the connection was unresponsive
4678 mFocusedWindow->consumeMotionCancel();
4679 mFocusedWindow->assertNoEvents();
4680 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004682 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004683 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004684}
4685
4686// If we have 2 windows with identical timeouts that are both unresponsive,
4687// it doesn't matter which order they should have ANR.
4688// But we should receive ANR for both.
4689TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4690 // Set the timeout for unfocused window to match the focused window
4691 mUnfocusedWindow->setDispatchingTimeout(10ms);
4692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4693
4694 tapOnFocusedWindow();
4695 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004696 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4697 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698
4699 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004700 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4701 mFocusedWindow->getToken() == anrConnectionToken2);
4702 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4703 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004704
4705 ASSERT_TRUE(mDispatcher->waitForIdle());
4706 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004707
4708 mFocusedWindow->consumeMotionDown();
4709 mFocusedWindow->consumeMotionUp();
4710 mUnfocusedWindow->consumeMotionOutside();
4711
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004712 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4713 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004714
4715 // Both applications should be marked as responsive, in any order
4716 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4717 mFocusedWindow->getToken() == responsiveToken2);
4718 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4719 mUnfocusedWindow->getToken() == responsiveToken2);
4720 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721}
4722
4723// If a window is already not responding, the second tap on the same window should be ignored.
4724// We should also log an error to account for the dropped event (not tested here).
4725// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4726TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4727 tapOnFocusedWindow();
4728 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4729 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4730 // Receive the events, but don't respond
4731 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4732 ASSERT_TRUE(downEventSequenceNum);
4733 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4734 ASSERT_TRUE(upEventSequenceNum);
4735 const std::chrono::duration timeout =
4736 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004737 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738
4739 // Tap once again
4740 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4743 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004744 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4746 FOCUSED_WINDOW_LOCATION));
4747 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4748 // valid touch target
4749 mUnfocusedWindow->assertNoEvents();
4750
4751 // Consume the first tap
4752 mFocusedWindow->finishEvent(*downEventSequenceNum);
4753 mFocusedWindow->finishEvent(*upEventSequenceNum);
4754 ASSERT_TRUE(mDispatcher->waitForIdle());
4755 // The second tap did not go to the focused window
4756 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004757 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004758 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759 mFakePolicy->assertNotifyAnrWasNotCalled();
4760}
4761
4762// If you tap outside of all windows, there will not be ANR
4763TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004764 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4766 LOCATION_OUTSIDE_ALL_WINDOWS));
4767 ASSERT_TRUE(mDispatcher->waitForIdle());
4768 mFakePolicy->assertNotifyAnrWasNotCalled();
4769}
4770
4771// Since the focused window is paused, tapping on it should not produce any events
4772TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4773 mFocusedWindow->setPaused(true);
4774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4775
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004776 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4778 FOCUSED_WINDOW_LOCATION));
4779
4780 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4781 ASSERT_TRUE(mDispatcher->waitForIdle());
4782 // Should not ANR because the window is paused, and touches shouldn't go to it
4783 mFakePolicy->assertNotifyAnrWasNotCalled();
4784
4785 mFocusedWindow->assertNoEvents();
4786 mUnfocusedWindow->assertNoEvents();
4787}
4788
4789/**
4790 * If a window is processing a motion event, and then a key event comes in, the key event should
4791 * not to to the focused window until the motion is processed.
4792 * If a different window becomes focused at this time, the key should go to that window instead.
4793 *
4794 * Warning!!!
4795 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4796 * and the injection timeout that we specify when injecting the key.
4797 * We must have the injection timeout (10ms) be smaller than
4798 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4799 *
4800 * If that value changes, this test should also change.
4801 */
4802TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4803 // Set a long ANR timeout to prevent it from triggering
4804 mFocusedWindow->setDispatchingTimeout(2s);
4805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4806
4807 tapOnUnfocusedWindow();
4808 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4809 ASSERT_TRUE(downSequenceNum);
4810 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4811 ASSERT_TRUE(upSequenceNum);
4812 // Don't finish the events yet, and send a key
4813 // Injection will succeed because we will eventually give up and send the key to the focused
4814 // window even if motions are still being processed.
4815
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004818 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4819 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820 // Key will not be sent to the window, yet, because the window is still processing events
4821 // and the key remains pending, waiting for the touch events to be processed
4822 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4823 ASSERT_FALSE(keySequenceNum);
4824
4825 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004826 mFocusedWindow->setFocusable(false);
4827 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004829 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830
4831 // Focus events should precede the key events
4832 mUnfocusedWindow->consumeFocusEvent(true);
4833 mFocusedWindow->consumeFocusEvent(false);
4834
4835 // Finish the tap events, which should unblock dispatcher
4836 mUnfocusedWindow->finishEvent(*downSequenceNum);
4837 mUnfocusedWindow->finishEvent(*upSequenceNum);
4838
4839 // Now that all queues are cleared and no backlog in the connections, the key event
4840 // can finally go to the newly focused "mUnfocusedWindow".
4841 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4842 mFocusedWindow->assertNoEvents();
4843 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004844 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004845}
4846
4847// When the touch stream is split across 2 windows, and one of them does not respond,
4848// then ANR should be raised and the touch should be canceled for the unresponsive window.
4849// The other window should not be affected by that.
4850TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4851 // Touch Window 1
4852 NotifyMotionArgs motionArgs =
4853 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4854 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4855 mDispatcher->notifyMotion(&motionArgs);
4856 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4857 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4858
4859 // Touch Window 2
4860 int32_t actionPointerDown =
4861 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4862
4863 motionArgs =
4864 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4865 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4866 mDispatcher->notifyMotion(&motionArgs);
4867
4868 const std::chrono::duration timeout =
4869 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004870 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004871
4872 mUnfocusedWindow->consumeMotionDown();
4873 mFocusedWindow->consumeMotionDown();
4874 // Focused window may or may not receive ACTION_MOVE
4875 // But it should definitely receive ACTION_CANCEL due to the ANR
4876 InputEvent* event;
4877 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4878 ASSERT_TRUE(moveOrCancelSequenceNum);
4879 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4880 ASSERT_NE(nullptr, event);
4881 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4882 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4883 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4884 mFocusedWindow->consumeMotionCancel();
4885 } else {
4886 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4887 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004889 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891 mUnfocusedWindow->assertNoEvents();
4892 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004893 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894}
4895
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004896/**
4897 * If we have no focused window, and a key comes in, we start the ANR timer.
4898 * The focused application should add a focused window before the timer runs out to prevent ANR.
4899 *
4900 * If the user touches another application during this time, the key should be dropped.
4901 * Next, if a new focused window comes in, without toggling the focused application,
4902 * then no ANR should occur.
4903 *
4904 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4905 * but in some cases the policy may not update the focused application.
4906 */
4907TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4908 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4909 std::make_shared<FakeApplicationHandle>();
4910 focusedApplication->setDispatchingTimeout(60ms);
4911 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4912 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4913 mFocusedWindow->setFocusable(false);
4914
4915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4916 mFocusedWindow->consumeFocusEvent(false);
4917
4918 // Send a key. The ANR timer should start because there is no focused window.
4919 // 'focusedApplication' will get blamed if this timer completes.
4920 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004921 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004922 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004923 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4924 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004926
4927 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4928 // then the injected touches won't cause the focused event to get dropped.
4929 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4930 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4931 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4932 // For this test, it means that the key would get delivered to the window once it becomes
4933 // focused.
4934 std::this_thread::sleep_for(10ms);
4935
4936 // Touch unfocused window. This should force the pending key to get dropped.
4937 NotifyMotionArgs motionArgs =
4938 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4939 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4940 mDispatcher->notifyMotion(&motionArgs);
4941
4942 // We do not consume the motion right away, because that would require dispatcher to first
4943 // process (== drop) the key event, and by that time, ANR will be raised.
4944 // Set the focused window first.
4945 mFocusedWindow->setFocusable(true);
4946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4947 setFocusedWindow(mFocusedWindow);
4948 mFocusedWindow->consumeFocusEvent(true);
4949 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4950 // to another application. This could be a bug / behaviour in the policy.
4951
4952 mUnfocusedWindow->consumeMotionDown();
4953
4954 ASSERT_TRUE(mDispatcher->waitForIdle());
4955 // Should not ANR because we actually have a focused window. It was just added too slowly.
4956 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4957}
4958
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004959// These tests ensure we cannot send touch events to a window that's positioned behind a window
4960// that has feature NO_INPUT_CHANNEL.
4961// Layout:
4962// Top (closest to user)
4963// mNoInputWindow (above all windows)
4964// mBottomWindow
4965// Bottom (furthest from user)
4966class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4967 virtual void SetUp() override {
4968 InputDispatcherTest::SetUp();
4969
4970 mApplication = std::make_shared<FakeApplicationHandle>();
4971 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4972 "Window without input channel", ADISPLAY_ID_DEFAULT,
4973 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4974
chaviw3277faf2021-05-19 16:45:23 -05004975 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004976 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4977 // It's perfectly valid for this window to not have an associated input channel
4978
4979 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4980 ADISPLAY_ID_DEFAULT);
4981 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4982
4983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4984 }
4985
4986protected:
4987 std::shared_ptr<FakeApplicationHandle> mApplication;
4988 sp<FakeWindowHandle> mNoInputWindow;
4989 sp<FakeWindowHandle> mBottomWindow;
4990};
4991
4992TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4993 PointF touchedPoint = {10, 10};
4994
4995 NotifyMotionArgs motionArgs =
4996 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4997 ADISPLAY_ID_DEFAULT, {touchedPoint});
4998 mDispatcher->notifyMotion(&motionArgs);
4999
5000 mNoInputWindow->assertNoEvents();
5001 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5002 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5003 // and therefore should prevent mBottomWindow from receiving touches
5004 mBottomWindow->assertNoEvents();
5005}
5006
5007/**
5008 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5009 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5010 */
5011TEST_F(InputDispatcherMultiWindowOcclusionTests,
5012 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5013 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5014 "Window with input channel and NO_INPUT_CHANNEL",
5015 ADISPLAY_ID_DEFAULT);
5016
chaviw3277faf2021-05-19 16:45:23 -05005017 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005018 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5020
5021 PointF touchedPoint = {10, 10};
5022
5023 NotifyMotionArgs motionArgs =
5024 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5025 ADISPLAY_ID_DEFAULT, {touchedPoint});
5026 mDispatcher->notifyMotion(&motionArgs);
5027
5028 mNoInputWindow->assertNoEvents();
5029 mBottomWindow->assertNoEvents();
5030}
5031
Vishnu Nair958da932020-08-21 17:12:37 -07005032class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5033protected:
5034 std::shared_ptr<FakeApplicationHandle> mApp;
5035 sp<FakeWindowHandle> mWindow;
5036 sp<FakeWindowHandle> mMirror;
5037
5038 virtual void SetUp() override {
5039 InputDispatcherTest::SetUp();
5040 mApp = std::make_shared<FakeApplicationHandle>();
5041 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5042 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5043 mWindow->getToken());
5044 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5045 mWindow->setFocusable(true);
5046 mMirror->setFocusable(true);
5047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5048 }
5049};
5050
5051TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5052 // Request focus on a mirrored window
5053 setFocusedWindow(mMirror);
5054
5055 // window gets focused
5056 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5058 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005059 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5060}
5061
5062// A focused & mirrored window remains focused only if the window and its mirror are both
5063// focusable.
5064TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5065 setFocusedWindow(mMirror);
5066
5067 // window gets focused
5068 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5070 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005071 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5073 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005074 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5075
5076 mMirror->setFocusable(false);
5077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5078
5079 // window loses focus since one of the windows associated with the token in not focusable
5080 mWindow->consumeFocusEvent(false);
5081
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5083 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005084 mWindow->assertNoEvents();
5085}
5086
5087// A focused & mirrored window remains focused until the window and its mirror both become
5088// invisible.
5089TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5090 setFocusedWindow(mMirror);
5091
5092 // window gets focused
5093 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5095 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005096 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5098 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005099 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5100
5101 mMirror->setVisible(false);
5102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5103
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5105 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005106 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5108 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005109 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5110
5111 mWindow->setVisible(false);
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5113
5114 // window loses focus only after all windows associated with the token become invisible.
5115 mWindow->consumeFocusEvent(false);
5116
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005117 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5118 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005119 mWindow->assertNoEvents();
5120}
5121
5122// A focused & mirrored window remains focused until both windows are removed.
5123TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5124 setFocusedWindow(mMirror);
5125
5126 // window gets focused
5127 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5129 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005130 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5132 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005133 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5134
5135 // single window is removed but the window token remains focused
5136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5137
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5139 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005140 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5142 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005143 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5144
5145 // Both windows are removed
5146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5147 mWindow->consumeFocusEvent(false);
5148
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005149 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5150 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005151 mWindow->assertNoEvents();
5152}
5153
5154// Focus request can be pending until one window becomes visible.
5155TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5156 // Request focus on an invisible mirror.
5157 mWindow->setVisible(false);
5158 mMirror->setVisible(false);
5159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5160 setFocusedWindow(mMirror);
5161
5162 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005164 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005165 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005166
5167 mMirror->setVisible(true);
5168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5169
5170 // window gets focused
5171 mWindow->consumeFocusEvent(true);
5172 // window gets the pending key event
5173 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5174}
Prabir Pradhan99987712020-11-10 18:43:05 -08005175
5176class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5177protected:
5178 std::shared_ptr<FakeApplicationHandle> mApp;
5179 sp<FakeWindowHandle> mWindow;
5180 sp<FakeWindowHandle> mSecondWindow;
5181
5182 void SetUp() override {
5183 InputDispatcherTest::SetUp();
5184 mApp = std::make_shared<FakeApplicationHandle>();
5185 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5186 mWindow->setFocusable(true);
5187 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5188 mSecondWindow->setFocusable(true);
5189
5190 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5192
5193 setFocusedWindow(mWindow);
5194 mWindow->consumeFocusEvent(true);
5195 }
5196
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005197 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5198 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005199 mDispatcher->notifyPointerCaptureChanged(&args);
5200 }
5201
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005202 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5203 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005204 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005205 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5206 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005207 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005208 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005209 }
5210};
5211
5212TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5213 // Ensure that capture cannot be obtained for unfocused windows.
5214 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5215 mFakePolicy->assertSetPointerCaptureNotCalled();
5216 mSecondWindow->assertNoEvents();
5217
5218 // Ensure that capture can be enabled from the focus window.
5219 requestAndVerifyPointerCapture(mWindow, true);
5220
5221 // Ensure that capture cannot be disabled from a window that does not have capture.
5222 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5223 mFakePolicy->assertSetPointerCaptureNotCalled();
5224
5225 // Ensure that capture can be disabled from the window with capture.
5226 requestAndVerifyPointerCapture(mWindow, false);
5227}
5228
5229TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005230 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005231
5232 setFocusedWindow(mSecondWindow);
5233
5234 // Ensure that the capture disabled event was sent first.
5235 mWindow->consumeCaptureEvent(false);
5236 mWindow->consumeFocusEvent(false);
5237 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005238 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005239
5240 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005241 notifyPointerCaptureChanged({});
5242 notifyPointerCaptureChanged(request);
5243 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005244 mWindow->assertNoEvents();
5245 mSecondWindow->assertNoEvents();
5246 mFakePolicy->assertSetPointerCaptureNotCalled();
5247}
5248
5249TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005250 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005251
5252 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005253 notifyPointerCaptureChanged({});
5254 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005255
5256 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005257 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005258 mWindow->consumeCaptureEvent(false);
5259 mWindow->assertNoEvents();
5260}
5261
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005262TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5263 requestAndVerifyPointerCapture(mWindow, true);
5264
5265 // The first window loses focus.
5266 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005267 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005268 mWindow->consumeCaptureEvent(false);
5269
5270 // Request Pointer Capture from the second window before the notification from InputReader
5271 // arrives.
5272 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005273 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005274
5275 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005276 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005277
5278 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005279 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005280
5281 mSecondWindow->consumeFocusEvent(true);
5282 mSecondWindow->consumeCaptureEvent(true);
5283}
5284
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005285TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5286 // App repeatedly enables and disables capture.
5287 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5288 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5289 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5290 mFakePolicy->assertSetPointerCaptureCalled(false);
5291 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5292 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5293
5294 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5295 // first request is now stale, this should do nothing.
5296 notifyPointerCaptureChanged(firstRequest);
5297 mWindow->assertNoEvents();
5298
5299 // InputReader notifies that the second request was enabled.
5300 notifyPointerCaptureChanged(secondRequest);
5301 mWindow->consumeCaptureEvent(true);
5302}
5303
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005304class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5305protected:
5306 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005307
5308 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5309 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5310
5311 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5312 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5313
5314 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5315 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5316 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5317 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5318 MAXIMUM_OBSCURING_OPACITY);
5319
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005320 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005321 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005322 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005323
5324 sp<FakeWindowHandle> mTouchWindow;
5325
5326 virtual void SetUp() override {
5327 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005328 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005329 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5330 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5331 }
5332
5333 virtual void TearDown() override {
5334 InputDispatcherTest::TearDown();
5335 mTouchWindow.clear();
5336 }
5337
chaviw3277faf2021-05-19 16:45:23 -05005338 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5339 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005340 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005341 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005342 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005343 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005344 return window;
5345 }
5346
5347 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5348 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5349 sp<FakeWindowHandle> window =
5350 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5351 // Generate an arbitrary PID based on the UID
5352 window->setOwnerInfo(1777 + (uid % 10000), uid);
5353 return window;
5354 }
5355
5356 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5357 NotifyMotionArgs args =
5358 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5359 ADISPLAY_ID_DEFAULT, points);
5360 mDispatcher->notifyMotion(&args);
5361 }
5362};
5363
5364TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005365 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005366 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005368
5369 touch();
5370
5371 mTouchWindow->assertNoEvents();
5372}
5373
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005374TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005375 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5376 const sp<FakeWindowHandle>& w =
5377 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5379
5380 touch();
5381
5382 mTouchWindow->assertNoEvents();
5383}
5384
5385TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005386 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5387 const sp<FakeWindowHandle>& w =
5388 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5389 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5390
5391 touch();
5392
5393 w->assertNoEvents();
5394}
5395
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005396TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005397 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005399
5400 touch();
5401
5402 mTouchWindow->consumeAnyMotionDown();
5403}
5404
5405TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005406 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005407 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005408 w->setFrame(Rect(0, 0, 50, 50));
5409 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005410
5411 touch({PointF{100, 100}});
5412
5413 mTouchWindow->consumeAnyMotionDown();
5414}
5415
5416TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005417 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005418 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5420
5421 touch();
5422
5423 mTouchWindow->consumeAnyMotionDown();
5424}
5425
5426TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5427 const sp<FakeWindowHandle>& w =
5428 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005430
5431 touch();
5432
5433 mTouchWindow->consumeAnyMotionDown();
5434}
5435
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005436TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5437 const sp<FakeWindowHandle>& w =
5438 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5440
5441 touch();
5442
5443 w->assertNoEvents();
5444}
5445
5446/**
5447 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5448 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5449 * window, the occluding window will still receive ACTION_OUTSIDE event.
5450 */
5451TEST_F(InputDispatcherUntrustedTouchesTest,
5452 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5453 const sp<FakeWindowHandle>& w =
5454 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005455 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5457
5458 touch();
5459
5460 w->consumeMotionOutside();
5461}
5462
5463TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5464 const sp<FakeWindowHandle>& w =
5465 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005466 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5468
5469 touch();
5470
5471 InputEvent* event = w->consume();
5472 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5473 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5474 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5475 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5476}
5477
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005478TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005479 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005480 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5481 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5483
5484 touch();
5485
5486 mTouchWindow->consumeAnyMotionDown();
5487}
5488
5489TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5490 const sp<FakeWindowHandle>& w =
5491 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5492 MAXIMUM_OBSCURING_OPACITY);
5493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005494
5495 touch();
5496
5497 mTouchWindow->consumeAnyMotionDown();
5498}
5499
5500TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005501 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005502 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5503 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5505
5506 touch();
5507
5508 mTouchWindow->assertNoEvents();
5509}
5510
5511TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5512 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5513 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005514 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5515 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005516 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005517 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5518 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5520
5521 touch();
5522
5523 mTouchWindow->assertNoEvents();
5524}
5525
5526TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5527 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5528 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005529 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5530 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005531 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005532 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5533 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5535
5536 touch();
5537
5538 mTouchWindow->consumeAnyMotionDown();
5539}
5540
5541TEST_F(InputDispatcherUntrustedTouchesTest,
5542 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5543 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005544 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5545 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005546 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005547 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5548 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5550
5551 touch();
5552
5553 mTouchWindow->consumeAnyMotionDown();
5554}
5555
5556TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5557 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005558 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5559 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005560 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005561 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5562 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005564
5565 touch();
5566
5567 mTouchWindow->assertNoEvents();
5568}
5569
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005570TEST_F(InputDispatcherUntrustedTouchesTest,
5571 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5572 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005573 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5574 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005575 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005576 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5577 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5579
5580 touch();
5581
5582 mTouchWindow->assertNoEvents();
5583}
5584
5585TEST_F(InputDispatcherUntrustedTouchesTest,
5586 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5587 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005588 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5589 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005590 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005591 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5592 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5594
5595 touch();
5596
5597 mTouchWindow->consumeAnyMotionDown();
5598}
5599
5600TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5601 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005602 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5603 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5605
5606 touch();
5607
5608 mTouchWindow->consumeAnyMotionDown();
5609}
5610
5611TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5612 const sp<FakeWindowHandle>& w =
5613 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5615
5616 touch();
5617
5618 mTouchWindow->consumeAnyMotionDown();
5619}
5620
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005621TEST_F(InputDispatcherUntrustedTouchesTest,
5622 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5623 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5624 const sp<FakeWindowHandle>& w =
5625 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5627
5628 touch();
5629
5630 mTouchWindow->assertNoEvents();
5631}
5632
5633TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5634 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5635 const sp<FakeWindowHandle>& w =
5636 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5638
5639 touch();
5640
5641 mTouchWindow->consumeAnyMotionDown();
5642}
5643
5644TEST_F(InputDispatcherUntrustedTouchesTest,
5645 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5646 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5647 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005648 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5649 OPACITY_ABOVE_THRESHOLD);
5650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5651
5652 touch();
5653
5654 mTouchWindow->consumeAnyMotionDown();
5655}
5656
5657TEST_F(InputDispatcherUntrustedTouchesTest,
5658 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5659 const sp<FakeWindowHandle>& w1 =
5660 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5661 OPACITY_BELOW_THRESHOLD);
5662 const sp<FakeWindowHandle>& w2 =
5663 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5664 OPACITY_BELOW_THRESHOLD);
5665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5666
5667 touch();
5668
5669 mTouchWindow->assertNoEvents();
5670}
5671
5672/**
5673 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5674 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5675 * (which alone would result in allowing touches) does not affect the blocking behavior.
5676 */
5677TEST_F(InputDispatcherUntrustedTouchesTest,
5678 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5679 const sp<FakeWindowHandle>& wB =
5680 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5681 OPACITY_BELOW_THRESHOLD);
5682 const sp<FakeWindowHandle>& wC =
5683 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5684 OPACITY_BELOW_THRESHOLD);
5685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5686
5687 touch();
5688
5689 mTouchWindow->assertNoEvents();
5690}
5691
5692/**
5693 * This test is testing that a window from a different UID but with same application token doesn't
5694 * block the touch. Apps can share the application token for close UI collaboration for example.
5695 */
5696TEST_F(InputDispatcherUntrustedTouchesTest,
5697 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5698 const sp<FakeWindowHandle>& w =
5699 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5700 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5702
5703 touch();
5704
5705 mTouchWindow->consumeAnyMotionDown();
5706}
5707
arthurhungb89ccb02020-12-30 16:19:01 +08005708class InputDispatcherDragTests : public InputDispatcherTest {
5709protected:
5710 std::shared_ptr<FakeApplicationHandle> mApp;
5711 sp<FakeWindowHandle> mWindow;
5712 sp<FakeWindowHandle> mSecondWindow;
5713 sp<FakeWindowHandle> mDragWindow;
5714
5715 void SetUp() override {
5716 InputDispatcherTest::SetUp();
5717 mApp = std::make_shared<FakeApplicationHandle>();
5718 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5719 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005720 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005721
5722 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5723 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005724 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005725
5726 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5728 }
5729
5730 // Start performing drag, we will create a drag window and transfer touch to it.
5731 void performDrag() {
5732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5734 {50, 50}))
5735 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5736
5737 // Window should receive motion event.
5738 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5739
5740 // The drag window covers the entire display
5741 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5742 mDispatcher->setInputWindows(
5743 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5744
5745 // Transfer touch focus to the drag window
5746 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5747 true /* isDragDrop */);
5748 mWindow->consumeMotionCancel();
5749 mDragWindow->consumeMotionDown();
5750 }
arthurhung6d4bed92021-03-17 11:59:33 +08005751
5752 // Start performing drag, we will create a drag window and transfer touch to it.
5753 void performStylusDrag() {
5754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5755 injectMotionEvent(mDispatcher,
5756 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5757 AINPUT_SOURCE_STYLUS)
5758 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5759 .pointer(PointerBuilder(0,
5760 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5761 .x(50)
5762 .y(50))
5763 .build()));
5764 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5765
5766 // The drag window covers the entire display
5767 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5768 mDispatcher->setInputWindows(
5769 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5770
5771 // Transfer touch focus to the drag window
5772 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5773 true /* isDragDrop */);
5774 mWindow->consumeMotionCancel();
5775 mDragWindow->consumeMotionDown();
5776 }
arthurhungb89ccb02020-12-30 16:19:01 +08005777};
5778
5779TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5780 performDrag();
5781
5782 // Move on window.
5783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5784 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5785 ADISPLAY_ID_DEFAULT, {50, 50}))
5786 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5787 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5788 mWindow->consumeDragEvent(false, 50, 50);
5789 mSecondWindow->assertNoEvents();
5790
5791 // Move to another window.
5792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5793 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5794 ADISPLAY_ID_DEFAULT, {150, 50}))
5795 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5796 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5797 mWindow->consumeDragEvent(true, 150, 50);
5798 mSecondWindow->consumeDragEvent(false, 50, 50);
5799
5800 // Move back to original window.
5801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5802 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5803 ADISPLAY_ID_DEFAULT, {50, 50}))
5804 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5805 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5806 mWindow->consumeDragEvent(false, 50, 50);
5807 mSecondWindow->consumeDragEvent(true, -50, 50);
5808
5809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5810 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5811 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5812 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5813 mWindow->assertNoEvents();
5814 mSecondWindow->assertNoEvents();
5815}
5816
arthurhungf452d0b2021-01-06 00:19:52 +08005817TEST_F(InputDispatcherDragTests, DragAndDrop) {
5818 performDrag();
5819
5820 // Move on window.
5821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5822 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5823 ADISPLAY_ID_DEFAULT, {50, 50}))
5824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5825 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5826 mWindow->consumeDragEvent(false, 50, 50);
5827 mSecondWindow->assertNoEvents();
5828
5829 // Move to another window.
5830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5831 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5832 ADISPLAY_ID_DEFAULT, {150, 50}))
5833 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5834 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5835 mWindow->consumeDragEvent(true, 150, 50);
5836 mSecondWindow->consumeDragEvent(false, 50, 50);
5837
5838 // drop to another window.
5839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5840 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5841 {150, 50}))
5842 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5843 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5844 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5845 mWindow->assertNoEvents();
5846 mSecondWindow->assertNoEvents();
5847}
5848
arthurhung6d4bed92021-03-17 11:59:33 +08005849TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5850 performStylusDrag();
5851
5852 // Move on window and keep button pressed.
5853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5854 injectMotionEvent(mDispatcher,
5855 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5856 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5857 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5858 .x(50)
5859 .y(50))
5860 .build()))
5861 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5862 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5863 mWindow->consumeDragEvent(false, 50, 50);
5864 mSecondWindow->assertNoEvents();
5865
5866 // Move to another window and release button, expect to drop item.
5867 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5868 injectMotionEvent(mDispatcher,
5869 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5870 .buttonState(0)
5871 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5872 .x(150)
5873 .y(50))
5874 .build()))
5875 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5876 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5877 mWindow->assertNoEvents();
5878 mSecondWindow->assertNoEvents();
5879 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5880
5881 // nothing to the window.
5882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5883 injectMotionEvent(mDispatcher,
5884 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5885 .buttonState(0)
5886 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5887 .x(150)
5888 .y(50))
5889 .build()))
5890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5891 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5892 mWindow->assertNoEvents();
5893 mSecondWindow->assertNoEvents();
5894}
5895
Arthur Hung6d0571e2021-04-09 20:18:16 +08005896TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5897 performDrag();
5898
5899 // Set second window invisible.
5900 mSecondWindow->setVisible(false);
5901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5902
5903 // Move on window.
5904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5905 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5906 ADISPLAY_ID_DEFAULT, {50, 50}))
5907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5908 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5909 mWindow->consumeDragEvent(false, 50, 50);
5910 mSecondWindow->assertNoEvents();
5911
5912 // Move to another window.
5913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5914 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5915 ADISPLAY_ID_DEFAULT, {150, 50}))
5916 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5917 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5918 mWindow->consumeDragEvent(true, 150, 50);
5919 mSecondWindow->assertNoEvents();
5920
5921 // drop to another window.
5922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5923 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5924 {150, 50}))
5925 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5926 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5927 mFakePolicy->assertDropTargetEquals(nullptr);
5928 mWindow->assertNoEvents();
5929 mSecondWindow->assertNoEvents();
5930}
5931
Vishnu Nair062a8672021-09-03 16:07:44 -07005932class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5933
5934TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5936 sp<FakeWindowHandle> window =
5937 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5938 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5939 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5940 window->setFocusable(true);
5941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5942 setFocusedWindow(window);
5943 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5944
5945 // With the flag set, window should not get any input
5946 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5947 mDispatcher->notifyKey(&keyArgs);
5948 window->assertNoEvents();
5949
5950 NotifyMotionArgs motionArgs =
5951 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5952 ADISPLAY_ID_DEFAULT);
5953 mDispatcher->notifyMotion(&motionArgs);
5954 window->assertNoEvents();
5955
5956 // With the flag cleared, the window should get input
5957 window->setInputFeatures({});
5958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5959
5960 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
5961 mDispatcher->notifyKey(&keyArgs);
5962 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
5963
5964 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5965 ADISPLAY_ID_DEFAULT);
5966 mDispatcher->notifyMotion(&motionArgs);
5967 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5968 window->assertNoEvents();
5969}
5970
5971TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
5972 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
5973 std::make_shared<FakeApplicationHandle>();
5974 sp<FakeWindowHandle> obscuringWindow =
5975 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
5976 ADISPLAY_ID_DEFAULT);
5977 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
5978 obscuringWindow->setOwnerInfo(111, 111);
5979 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
5980 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5981 sp<FakeWindowHandle> window =
5982 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5983 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
5984 window->setOwnerInfo(222, 222);
5985 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5986 window->setFocusable(true);
5987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
5988 setFocusedWindow(window);
5989 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5990
5991 // With the flag set, window should not get any input
5992 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5993 mDispatcher->notifyKey(&keyArgs);
5994 window->assertNoEvents();
5995
5996 NotifyMotionArgs motionArgs =
5997 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5998 ADISPLAY_ID_DEFAULT);
5999 mDispatcher->notifyMotion(&motionArgs);
6000 window->assertNoEvents();
6001
6002 // With the flag cleared, the window should get input
6003 window->setInputFeatures({});
6004 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6005
6006 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6007 mDispatcher->notifyKey(&keyArgs);
6008 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6009
6010 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6011 ADISPLAY_ID_DEFAULT);
6012 mDispatcher->notifyMotion(&motionArgs);
6013 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6014 window->assertNoEvents();
6015}
6016
6017TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6018 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6019 std::make_shared<FakeApplicationHandle>();
6020 sp<FakeWindowHandle> obscuringWindow =
6021 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6022 ADISPLAY_ID_DEFAULT);
6023 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6024 obscuringWindow->setOwnerInfo(111, 111);
6025 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6026 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6027 sp<FakeWindowHandle> window =
6028 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6029 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6030 window->setOwnerInfo(222, 222);
6031 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6032 window->setFocusable(true);
6033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6034 setFocusedWindow(window);
6035 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6036
6037 // With the flag set, window should not get any input
6038 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6039 mDispatcher->notifyKey(&keyArgs);
6040 window->assertNoEvents();
6041
6042 NotifyMotionArgs motionArgs =
6043 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6044 ADISPLAY_ID_DEFAULT);
6045 mDispatcher->notifyMotion(&motionArgs);
6046 window->assertNoEvents();
6047
6048 // When the window is no longer obscured because it went on top, it should get input
6049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6050
6051 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6052 mDispatcher->notifyKey(&keyArgs);
6053 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6054
6055 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6056 ADISPLAY_ID_DEFAULT);
6057 mDispatcher->notifyMotion(&motionArgs);
6058 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6059 window->assertNoEvents();
6060}
6061
Antonio Kantekf16f2832021-09-28 04:39:20 +00006062class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6063protected:
6064 std::shared_ptr<FakeApplicationHandle> mApp;
6065 sp<FakeWindowHandle> mWindow;
6066 sp<FakeWindowHandle> mSecondWindow;
6067
6068 void SetUp() override {
6069 InputDispatcherTest::SetUp();
6070
6071 mApp = std::make_shared<FakeApplicationHandle>();
6072 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6073 mWindow->setFocusable(true);
6074 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6075 mSecondWindow->setFocusable(true);
6076
6077 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6079
6080 setFocusedWindow(mWindow);
6081 mWindow->consumeFocusEvent(true);
6082 }
6083
6084 void changeAndVerifyTouchMode(bool inTouchMode) {
6085 mDispatcher->setInTouchMode(inTouchMode);
6086 mWindow->consumeTouchModeEvent(inTouchMode);
6087 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6088 }
6089};
6090
6091TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6092 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6093}
6094
6095TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6096 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6097 mWindow->assertNoEvents();
6098 mSecondWindow->assertNoEvents();
6099}
6100
Garfield Tane84e6f92019-08-29 17:28:41 -07006101} // namespace android::inputdispatcher