blob: ffacfb1b1f7ffae1f2667155eb62dce74d29a648 [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/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001631 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1632 * with the following differences:
1633 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1634 * clean up the connection.
1635 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1636 * Ensure that there's no crash in the dispatcher.
1637 */
1638TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1640 sp<FakeWindowHandle> foregroundWindow =
1641 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1642 foregroundWindow->setHasWallpaper(true);
1643 sp<FakeWindowHandle> wallpaperWindow =
1644 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1645 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1646 constexpr int expectedWallpaperFlags =
1647 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1648
1649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1650 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1651 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1652 {100, 200}))
1653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1654
1655 // Both foreground window and its wallpaper should receive the touch down
1656 foregroundWindow->consumeMotionDown();
1657 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1658
1659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1660 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1661 ADISPLAY_ID_DEFAULT, {110, 200}))
1662 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1663
1664 foregroundWindow->consumeMotionMove();
1665 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1666
1667 // Wallpaper closes its channel, but the window remains.
1668 wallpaperWindow->destroyReceiver();
1669 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1670
1671 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1672 // is no longer valid.
1673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1674 foregroundWindow->consumeMotionCancel();
1675}
1676
1677/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001678 * A single window that receives touch (on top), and a wallpaper window underneath it.
1679 * The top window gets a multitouch gesture.
1680 * Ensure that wallpaper gets the same gesture.
1681 */
1682TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1683 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1684 sp<FakeWindowHandle> window =
1685 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1686 window->setHasWallpaper(true);
1687
1688 sp<FakeWindowHandle> wallpaperWindow =
1689 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1690 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1691 constexpr int expectedWallpaperFlags =
1692 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1693
1694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1695
1696 // Touch down on top window
1697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1699 {100, 100}))
1700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1701
1702 // Both top window and its wallpaper should receive the touch down
1703 window->consumeMotionDown();
1704 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1705
1706 // Second finger down on the top window
1707 const MotionEvent secondFingerDownEvent =
1708 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1709 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1710 AINPUT_SOURCE_TOUCHSCREEN)
1711 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1712 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1713 .x(100)
1714 .y(100))
1715 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1716 .x(150)
1717 .y(150))
1718 .build();
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1721 InputEventInjectionSync::WAIT_FOR_RESULT))
1722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1723
1724 window->consumeMotionPointerDown(1 /* pointerIndex */);
1725 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1726 expectedWallpaperFlags);
1727 window->assertNoEvents();
1728 wallpaperWindow->assertNoEvents();
1729}
1730
1731/**
1732 * Two windows: a window on the left and window on the right.
1733 * A third window, wallpaper, is behind both windows, and spans both top windows.
1734 * The first touch down goes to the left window. A second pointer touches down on the right window.
1735 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1736 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1737 * ACTION_POINTER_DOWN(1).
1738 */
1739TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1740 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1741 sp<FakeWindowHandle> leftWindow =
1742 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1743 leftWindow->setFrame(Rect(0, 0, 200, 200));
1744 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1745 leftWindow->setHasWallpaper(true);
1746
1747 sp<FakeWindowHandle> rightWindow =
1748 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1749 rightWindow->setFrame(Rect(200, 0, 400, 200));
1750 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1751 rightWindow->setHasWallpaper(true);
1752
1753 sp<FakeWindowHandle> wallpaperWindow =
1754 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1755 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1756 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1757 constexpr int expectedWallpaperFlags =
1758 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1759
1760 mDispatcher->setInputWindows(
1761 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1762
1763 // Touch down on left window
1764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1766 {100, 100}))
1767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1768
1769 // Both foreground window and its wallpaper should receive the touch down
1770 leftWindow->consumeMotionDown();
1771 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1772
1773 // Second finger down on the right window
1774 const MotionEvent secondFingerDownEvent =
1775 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1776 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1777 AINPUT_SOURCE_TOUCHSCREEN)
1778 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1779 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1780 .x(100)
1781 .y(100))
1782 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1783 .x(300)
1784 .y(100))
1785 .build();
1786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1787 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1788 InputEventInjectionSync::WAIT_FOR_RESULT))
1789 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1790
1791 leftWindow->consumeMotionMove();
1792 // Since the touch is split, right window gets ACTION_DOWN
1793 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1794 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1795 expectedWallpaperFlags);
1796
1797 // Now, leftWindow, which received the first finger, disappears.
1798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1799 leftWindow->consumeMotionCancel();
1800 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1801 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1802
1803 // The pointer that's still down on the right window moves, and goes to the right window only.
1804 // As far as the dispatcher's concerned though, both pointers are still present.
1805 const MotionEvent secondFingerMoveEvent =
1806 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1807 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1808 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1809 .x(100)
1810 .y(100))
1811 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1812 .x(310)
1813 .y(110))
1814 .build();
1815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1816 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1817 InputEventInjectionSync::WAIT_FOR_RESULT));
1818 rightWindow->consumeMotionMove();
1819
1820 leftWindow->assertNoEvents();
1821 rightWindow->assertNoEvents();
1822 wallpaperWindow->assertNoEvents();
1823}
1824
Garfield Tandf26e862020-07-01 20:18:19 -07001825TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001826 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001827 sp<FakeWindowHandle> windowLeft =
1828 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1829 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001830 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001831 sp<FakeWindowHandle> windowRight =
1832 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1833 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001834 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001835
1836 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1837
1838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1839
1840 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001841 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001842 injectMotionEvent(mDispatcher,
1843 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1844 AINPUT_SOURCE_MOUSE)
1845 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1846 .x(900)
1847 .y(400))
1848 .build()));
1849 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1850 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1851 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1852 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1853
1854 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001856 injectMotionEvent(mDispatcher,
1857 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1858 AINPUT_SOURCE_MOUSE)
1859 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1860 .x(300)
1861 .y(400))
1862 .build()));
1863 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1864 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1865 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1866 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1867 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1868 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1869
1870 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1874 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1875 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1876 .x(300)
1877 .y(400))
1878 .build()));
1879 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1880
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001882 injectMotionEvent(mDispatcher,
1883 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1884 AINPUT_SOURCE_MOUSE)
1885 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1886 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1887 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1888 .x(300)
1889 .y(400))
1890 .build()));
1891 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1892 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001895 injectMotionEvent(mDispatcher,
1896 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1897 AINPUT_SOURCE_MOUSE)
1898 .buttonState(0)
1899 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1900 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1901 .x(300)
1902 .y(400))
1903 .build()));
1904 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1905 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1906
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001908 injectMotionEvent(mDispatcher,
1909 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1910 .buttonState(0)
1911 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1912 .x(300)
1913 .y(400))
1914 .build()));
1915 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1916
1917 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001919 injectMotionEvent(mDispatcher,
1920 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1921 AINPUT_SOURCE_MOUSE)
1922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1923 .x(900)
1924 .y(400))
1925 .build()));
1926 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1927 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1928 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1929 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1930 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1931 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1932}
1933
1934// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1935// directly in this test.
1936TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001938 sp<FakeWindowHandle> window =
1939 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1940 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001941 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001942
1943 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1944
1945 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1946
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001948 injectMotionEvent(mDispatcher,
1949 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1950 AINPUT_SOURCE_MOUSE)
1951 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1952 .x(300)
1953 .y(400))
1954 .build()));
1955 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1956 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1957
1958 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001960 injectMotionEvent(mDispatcher,
1961 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1962 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1963 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1964 .x(300)
1965 .y(400))
1966 .build()));
1967 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1972 AINPUT_SOURCE_MOUSE)
1973 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1974 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1975 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1976 .x(300)
1977 .y(400))
1978 .build()));
1979 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1980 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1981
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001983 injectMotionEvent(mDispatcher,
1984 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1985 AINPUT_SOURCE_MOUSE)
1986 .buttonState(0)
1987 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1988 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1989 .x(300)
1990 .y(400))
1991 .build()));
1992 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1993 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1994
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001996 injectMotionEvent(mDispatcher,
1997 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1998 .buttonState(0)
1999 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2000 .x(300)
2001 .y(400))
2002 .build()));
2003 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002006 injectMotionEvent(mDispatcher,
2007 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2008 AINPUT_SOURCE_MOUSE)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2014 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2015}
2016
Garfield Tan00f511d2019-06-12 16:55:40 -07002017TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002019
2020 sp<FakeWindowHandle> windowLeft =
2021 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2022 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002023 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002024 sp<FakeWindowHandle> windowRight =
2025 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2026 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002027 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002028
2029 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2030
Arthur Hung72d8dc32020-03-28 00:48:39 +00002031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002032
2033 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2034 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002036 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002037 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002038 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002039 windowRight->assertNoEvents();
2040}
2041
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002042TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002044 sp<FakeWindowHandle> window =
2045 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002046 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002047
Arthur Hung72d8dc32020-03-28 00:48:39 +00002048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002049 setFocusedWindow(window);
2050
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002051 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002052
2053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2054 mDispatcher->notifyKey(&keyArgs);
2055
2056 // Window should receive key down event.
2057 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2058
2059 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2060 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002061 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002062 mDispatcher->notifyDeviceReset(&args);
2063 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2064 AKEY_EVENT_FLAG_CANCELED);
2065}
2066
2067TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002068 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002069 sp<FakeWindowHandle> window =
2070 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2071
Arthur Hung72d8dc32020-03-28 00:48:39 +00002072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002073
2074 NotifyMotionArgs motionArgs =
2075 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2076 ADISPLAY_ID_DEFAULT);
2077 mDispatcher->notifyMotion(&motionArgs);
2078
2079 // Window should receive motion down event.
2080 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2081
2082 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2083 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002084 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002085 mDispatcher->notifyDeviceReset(&args);
2086 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2087 0 /*expectedFlags*/);
2088}
2089
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002090/**
2091 * Ensure the correct coordinate spaces are used by InputDispatcher.
2092 *
2093 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2094 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2095 * space.
2096 */
2097class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2098public:
2099 void SetUp() override {
2100 InputDispatcherTest::SetUp();
2101 mDisplayInfos.clear();
2102 mWindowInfos.clear();
2103 }
2104
2105 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2106 gui::DisplayInfo info;
2107 info.displayId = displayId;
2108 info.transform = transform;
2109 mDisplayInfos.push_back(std::move(info));
2110 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2111 }
2112
2113 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2114 mWindowInfos.push_back(*windowHandle->getInfo());
2115 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2116 }
2117
2118 // Set up a test scenario where the display has a scaled projection and there are two windows
2119 // on the display.
2120 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2121 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2122 // respectively.
2123 ui::Transform displayTransform;
2124 displayTransform.set(2, 0, 0, 4);
2125 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2126
2127 std::shared_ptr<FakeApplicationHandle> application =
2128 std::make_shared<FakeApplicationHandle>();
2129
2130 // Add two windows to the display. Their frames are represented in the display space.
2131 sp<FakeWindowHandle> firstWindow =
2132 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2133 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2134 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2135 addWindow(firstWindow);
2136
2137 sp<FakeWindowHandle> secondWindow =
2138 new FakeWindowHandle(application, mDispatcher, "Second Window",
2139 ADISPLAY_ID_DEFAULT);
2140 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2141 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2142 addWindow(secondWindow);
2143 return {std::move(firstWindow), std::move(secondWindow)};
2144 }
2145
2146private:
2147 std::vector<gui::DisplayInfo> mDisplayInfos;
2148 std::vector<gui::WindowInfo> mWindowInfos;
2149};
2150
2151TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2152 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2153 // Send down to the first window. The point is represented in the display space. The point is
2154 // selected so that if the hit test was done with the transform applied to it, then it would
2155 // end up in the incorrect window.
2156 NotifyMotionArgs downMotionArgs =
2157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2158 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2159 mDispatcher->notifyMotion(&downMotionArgs);
2160
2161 firstWindow->consumeMotionDown();
2162 secondWindow->assertNoEvents();
2163}
2164
2165// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2166// the event should be treated as being in the logical display space.
2167TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2168 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2169 // Send down to the first window. The point is represented in the logical display space. The
2170 // point is selected so that if the hit test was done in logical display space, then it would
2171 // end up in the incorrect window.
2172 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2173 PointF{75 * 2, 55 * 4});
2174
2175 firstWindow->consumeMotionDown();
2176 secondWindow->assertNoEvents();
2177}
2178
2179TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2180 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2181
2182 // Send down to the second window.
2183 NotifyMotionArgs downMotionArgs =
2184 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2185 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2186 mDispatcher->notifyMotion(&downMotionArgs);
2187
2188 firstWindow->assertNoEvents();
2189 const MotionEvent* event = secondWindow->consumeMotion();
2190 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2191
2192 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2193 EXPECT_EQ(300, event->getRawX(0));
2194 EXPECT_EQ(880, event->getRawY(0));
2195
2196 // Ensure that the x and y values are in the window's coordinate space.
2197 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2198 // the logical display space. This will be the origin of the window space.
2199 EXPECT_EQ(100, event->getX(0));
2200 EXPECT_EQ(80, event->getY(0));
2201}
2202
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002203using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2204 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002205
2206class TransferTouchFixture : public InputDispatcherTest,
2207 public ::testing::WithParamInterface<TransferFunction> {};
2208
2209TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002210 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002211
2212 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002213 sp<FakeWindowHandle> firstWindow =
2214 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2215 sp<FakeWindowHandle> secondWindow =
2216 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002217
2218 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002220
2221 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002222 NotifyMotionArgs downMotionArgs =
2223 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2224 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002225 mDispatcher->notifyMotion(&downMotionArgs);
2226 // Only the first window should get the down event
2227 firstWindow->consumeMotionDown();
2228 secondWindow->assertNoEvents();
2229
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002230 // Transfer touch to the second window
2231 TransferFunction f = GetParam();
2232 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2233 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002234 // The first window gets cancel and the second gets down
2235 firstWindow->consumeMotionCancel();
2236 secondWindow->consumeMotionDown();
2237
2238 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002239 NotifyMotionArgs upMotionArgs =
2240 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2241 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002242 mDispatcher->notifyMotion(&upMotionArgs);
2243 // The first window gets no events and the second gets up
2244 firstWindow->assertNoEvents();
2245 secondWindow->consumeMotionUp();
2246}
2247
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002248TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002249 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002250
2251 PointF touchPoint = {10, 10};
2252
2253 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002254 sp<FakeWindowHandle> firstWindow =
2255 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2256 sp<FakeWindowHandle> secondWindow =
2257 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002258
2259 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002261
2262 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002263 NotifyMotionArgs downMotionArgs =
2264 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2265 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266 mDispatcher->notifyMotion(&downMotionArgs);
2267 // Only the first window should get the down event
2268 firstWindow->consumeMotionDown();
2269 secondWindow->assertNoEvents();
2270
2271 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002272 NotifyMotionArgs pointerDownMotionArgs =
2273 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2274 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2275 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2276 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002277 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2278 // Only the first window should get the pointer down event
2279 firstWindow->consumeMotionPointerDown(1);
2280 secondWindow->assertNoEvents();
2281
2282 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002283 TransferFunction f = GetParam();
2284 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2285 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002286 // The first window gets cancel and the second gets down and pointer down
2287 firstWindow->consumeMotionCancel();
2288 secondWindow->consumeMotionDown();
2289 secondWindow->consumeMotionPointerDown(1);
2290
2291 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002292 NotifyMotionArgs pointerUpMotionArgs =
2293 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2294 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2295 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2296 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002297 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2298 // The first window gets nothing and the second gets pointer up
2299 firstWindow->assertNoEvents();
2300 secondWindow->consumeMotionPointerUp(1);
2301
2302 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002303 NotifyMotionArgs upMotionArgs =
2304 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2305 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002306 mDispatcher->notifyMotion(&upMotionArgs);
2307 // The first window gets nothing and the second gets up
2308 firstWindow->assertNoEvents();
2309 secondWindow->consumeMotionUp();
2310}
2311
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002312// For the cases of single pointer touch and two pointers non-split touch, the api's
2313// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2314// for the case where there are multiple pointers split across several windows.
2315INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2316 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002317 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2318 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002319 return dispatcher->transferTouch(destChannelToken);
2320 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002321 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2322 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002323 return dispatcher->transferTouchFocus(from, to,
2324 false /*isDragAndDrop*/);
2325 }));
2326
Svet Ganov5d3bc372020-01-26 23:11:07 -08002327TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002329
2330 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002331 sp<FakeWindowHandle> firstWindow =
2332 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002333 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002334 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002335
2336 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002337 sp<FakeWindowHandle> secondWindow =
2338 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002339 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002340 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002341
2342 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344
2345 PointF pointInFirst = {300, 200};
2346 PointF pointInSecond = {300, 600};
2347
2348 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002349 NotifyMotionArgs firstDownMotionArgs =
2350 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2351 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002352 mDispatcher->notifyMotion(&firstDownMotionArgs);
2353 // Only the first window should get the down event
2354 firstWindow->consumeMotionDown();
2355 secondWindow->assertNoEvents();
2356
2357 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002358 NotifyMotionArgs secondDownMotionArgs =
2359 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2360 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2361 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2362 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002363 mDispatcher->notifyMotion(&secondDownMotionArgs);
2364 // The first window gets a move and the second a down
2365 firstWindow->consumeMotionMove();
2366 secondWindow->consumeMotionDown();
2367
2368 // Transfer touch focus to the second window
2369 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2370 // The first window gets cancel and the new gets pointer down (it already saw down)
2371 firstWindow->consumeMotionCancel();
2372 secondWindow->consumeMotionPointerDown(1);
2373
2374 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002375 NotifyMotionArgs pointerUpMotionArgs =
2376 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2377 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2378 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2379 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002380 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2381 // The first window gets nothing and the second gets pointer up
2382 firstWindow->assertNoEvents();
2383 secondWindow->consumeMotionPointerUp(1);
2384
2385 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002386 NotifyMotionArgs upMotionArgs =
2387 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2388 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389 mDispatcher->notifyMotion(&upMotionArgs);
2390 // The first window gets nothing and the second gets up
2391 firstWindow->assertNoEvents();
2392 secondWindow->consumeMotionUp();
2393}
2394
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002395// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2396// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2397// touch is not supported, so the touch should continue on those windows and the transferred-to
2398// window should get nothing.
2399TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2400 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2401
2402 // Create a non touch modal window that supports split touch
2403 sp<FakeWindowHandle> firstWindow =
2404 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2405 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002406 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002407
2408 // Create a non touch modal window that supports split touch
2409 sp<FakeWindowHandle> secondWindow =
2410 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2411 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002412 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002413
2414 // Add the windows to the dispatcher
2415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2416
2417 PointF pointInFirst = {300, 200};
2418 PointF pointInSecond = {300, 600};
2419
2420 // Send down to the first window
2421 NotifyMotionArgs firstDownMotionArgs =
2422 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2423 ADISPLAY_ID_DEFAULT, {pointInFirst});
2424 mDispatcher->notifyMotion(&firstDownMotionArgs);
2425 // Only the first window should get the down event
2426 firstWindow->consumeMotionDown();
2427 secondWindow->assertNoEvents();
2428
2429 // Send down to the second window
2430 NotifyMotionArgs secondDownMotionArgs =
2431 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2432 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2433 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2434 {pointInFirst, pointInSecond});
2435 mDispatcher->notifyMotion(&secondDownMotionArgs);
2436 // The first window gets a move and the second a down
2437 firstWindow->consumeMotionMove();
2438 secondWindow->consumeMotionDown();
2439
2440 // Transfer touch focus to the second window
2441 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2442 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2443 ASSERT_FALSE(transferred);
2444 firstWindow->assertNoEvents();
2445 secondWindow->assertNoEvents();
2446
2447 // The rest of the dispatch should proceed as normal
2448 // Send pointer up to the second window
2449 NotifyMotionArgs pointerUpMotionArgs =
2450 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2451 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2452 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2453 {pointInFirst, pointInSecond});
2454 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2455 // The first window gets MOVE and the second gets pointer up
2456 firstWindow->consumeMotionMove();
2457 secondWindow->consumeMotionUp();
2458
2459 // Send up event to the first window
2460 NotifyMotionArgs upMotionArgs =
2461 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2462 ADISPLAY_ID_DEFAULT);
2463 mDispatcher->notifyMotion(&upMotionArgs);
2464 // The first window gets nothing and the second gets up
2465 firstWindow->consumeMotionUp();
2466 secondWindow->assertNoEvents();
2467}
2468
Arthur Hungabbb9d82021-09-01 14:52:30 +00002469// This case will create two windows and one mirrored window on the default display and mirror
2470// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2471// the windows info of second display before default display.
2472TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2473 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2474 sp<FakeWindowHandle> firstWindowInPrimary =
2475 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2476 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2477 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2478 sp<FakeWindowHandle> secondWindowInPrimary =
2479 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2480 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2481 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2482
2483 sp<FakeWindowHandle> mirrorWindowInPrimary =
2484 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2485 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2486 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2487
2488 sp<FakeWindowHandle> firstWindowInSecondary =
2489 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2490 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2491 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2492
2493 sp<FakeWindowHandle> secondWindowInSecondary =
2494 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2495 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2496 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2497
2498 // Update window info, let it find window handle of second display first.
2499 mDispatcher->setInputWindows(
2500 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2501 {ADISPLAY_ID_DEFAULT,
2502 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2503
2504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2505 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2506 {50, 50}))
2507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2508
2509 // Window should receive motion event.
2510 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2511
2512 // Transfer touch focus
2513 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2514 secondWindowInPrimary->getToken()));
2515 // The first window gets cancel.
2516 firstWindowInPrimary->consumeMotionCancel();
2517 secondWindowInPrimary->consumeMotionDown();
2518
2519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2520 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2521 ADISPLAY_ID_DEFAULT, {150, 50}))
2522 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2523 firstWindowInPrimary->assertNoEvents();
2524 secondWindowInPrimary->consumeMotionMove();
2525
2526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2527 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2528 {150, 50}))
2529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2530 firstWindowInPrimary->assertNoEvents();
2531 secondWindowInPrimary->consumeMotionUp();
2532}
2533
2534// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2535// 'transferTouch' api.
2536TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2538 sp<FakeWindowHandle> firstWindowInPrimary =
2539 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2540 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2541 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2542 sp<FakeWindowHandle> secondWindowInPrimary =
2543 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2544 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2545 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2546
2547 sp<FakeWindowHandle> mirrorWindowInPrimary =
2548 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2549 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2550 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2551
2552 sp<FakeWindowHandle> firstWindowInSecondary =
2553 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2554 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2555 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2556
2557 sp<FakeWindowHandle> secondWindowInSecondary =
2558 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2559 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2560 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2561
2562 // Update window info, let it find window handle of second display first.
2563 mDispatcher->setInputWindows(
2564 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2565 {ADISPLAY_ID_DEFAULT,
2566 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2567
2568 // Touch on second display.
2569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2570 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2572
2573 // Window should receive motion event.
2574 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2575
2576 // Transfer touch focus
2577 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2578
2579 // The first window gets cancel.
2580 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2581 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2582
2583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2584 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2585 SECOND_DISPLAY_ID, {150, 50}))
2586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2587 firstWindowInPrimary->assertNoEvents();
2588 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2589
2590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2591 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2593 firstWindowInPrimary->assertNoEvents();
2594 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2595}
2596
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002597TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002598 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002599 sp<FakeWindowHandle> window =
2600 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2601
Vishnu Nair47074b82020-08-14 11:54:47 -07002602 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002604 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002605
2606 window->consumeFocusEvent(true);
2607
2608 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2609 mDispatcher->notifyKey(&keyArgs);
2610
2611 // Window should receive key down event.
2612 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2613}
2614
2615TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002617 sp<FakeWindowHandle> window =
2618 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2619
Arthur Hung72d8dc32020-03-28 00:48:39 +00002620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002621
2622 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2623 mDispatcher->notifyKey(&keyArgs);
2624 mDispatcher->waitForIdle();
2625
2626 window->assertNoEvents();
2627}
2628
2629// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2630TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002631 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002632 sp<FakeWindowHandle> window =
2633 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2634
Arthur Hung72d8dc32020-03-28 00:48:39 +00002635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636
2637 // Send key
2638 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2639 mDispatcher->notifyKey(&keyArgs);
2640 // Send motion
2641 NotifyMotionArgs motionArgs =
2642 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2643 ADISPLAY_ID_DEFAULT);
2644 mDispatcher->notifyMotion(&motionArgs);
2645
2646 // Window should receive only the motion event
2647 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2648 window->assertNoEvents(); // Key event or focus event will not be received
2649}
2650
arthurhungea3f4fc2020-12-21 23:18:53 +08002651TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2652 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2653
2654 // Create first non touch modal window that supports split touch
2655 sp<FakeWindowHandle> firstWindow =
2656 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2657 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002658 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002659
2660 // Create second non touch modal window that supports split touch
2661 sp<FakeWindowHandle> secondWindow =
2662 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2663 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002664 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002665
2666 // Add the windows to the dispatcher
2667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2668
2669 PointF pointInFirst = {300, 200};
2670 PointF pointInSecond = {300, 600};
2671
2672 // Send down to the first window
2673 NotifyMotionArgs firstDownMotionArgs =
2674 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2675 ADISPLAY_ID_DEFAULT, {pointInFirst});
2676 mDispatcher->notifyMotion(&firstDownMotionArgs);
2677 // Only the first window should get the down event
2678 firstWindow->consumeMotionDown();
2679 secondWindow->assertNoEvents();
2680
2681 // Send down to the second window
2682 NotifyMotionArgs secondDownMotionArgs =
2683 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2684 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2685 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2686 {pointInFirst, pointInSecond});
2687 mDispatcher->notifyMotion(&secondDownMotionArgs);
2688 // The first window gets a move and the second a down
2689 firstWindow->consumeMotionMove();
2690 secondWindow->consumeMotionDown();
2691
2692 // Send pointer cancel to the second window
2693 NotifyMotionArgs pointerUpMotionArgs =
2694 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2695 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2696 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2697 {pointInFirst, pointInSecond});
2698 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2699 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2700 // The first window gets move and the second gets cancel.
2701 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2702 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2703
2704 // Send up event.
2705 NotifyMotionArgs upMotionArgs =
2706 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2707 ADISPLAY_ID_DEFAULT);
2708 mDispatcher->notifyMotion(&upMotionArgs);
2709 // The first window gets up and the second gets nothing.
2710 firstWindow->consumeMotionUp();
2711 secondWindow->assertNoEvents();
2712}
2713
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002714TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2715 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2716
2717 sp<FakeWindowHandle> window =
2718 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2719 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2720 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2721 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2722 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2723
2724 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2725 window->assertNoEvents();
2726 mDispatcher->waitForIdle();
2727}
2728
chaviwd1c23182019-12-20 18:44:56 -08002729class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002730public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002731 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002732 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002733 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002734 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002735 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002736 }
2737
chaviwd1c23182019-12-20 18:44:56 -08002738 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2739
2740 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2741 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2742 expectedDisplayId, expectedFlags);
2743 }
2744
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002745 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2746
2747 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2748
chaviwd1c23182019-12-20 18:44:56 -08002749 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2750 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2751 expectedDisplayId, expectedFlags);
2752 }
2753
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002754 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2755 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2756 expectedDisplayId, expectedFlags);
2757 }
2758
chaviwd1c23182019-12-20 18:44:56 -08002759 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2760 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2761 expectedDisplayId, expectedFlags);
2762 }
2763
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002764 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2765 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2766 expectedDisplayId, expectedFlags);
2767 }
2768
Evan Rosky84f07f02021-04-16 10:42:42 -07002769 MotionEvent* consumeMotion() {
2770 InputEvent* event = mInputReceiver->consume();
2771 if (!event) {
2772 ADD_FAILURE() << "No event was produced";
2773 return nullptr;
2774 }
2775 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2776 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2777 return nullptr;
2778 }
2779 return static_cast<MotionEvent*>(event);
2780 }
2781
chaviwd1c23182019-12-20 18:44:56 -08002782 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2783
2784private:
2785 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002786};
2787
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002788/**
2789 * Two entities that receive touch: A window, and a global monitor.
2790 * The touch goes to the window, and then the window disappears.
2791 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2792 * for the monitor, as well.
2793 * 1. foregroundWindow
2794 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2795 */
2796TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2797 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2798 sp<FakeWindowHandle> window =
2799 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2800
2801 FakeMonitorReceiver monitor =
2802 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2803 false /*isGestureMonitor*/);
2804
2805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2807 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2808 {100, 200}))
2809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2810
2811 // Both the foreground window and the global monitor should receive the touch down
2812 window->consumeMotionDown();
2813 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2814
2815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2816 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2817 ADISPLAY_ID_DEFAULT, {110, 200}))
2818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2819
2820 window->consumeMotionMove();
2821 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2822
2823 // Now the foreground window goes away
2824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2825 window->consumeMotionCancel();
2826 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2827
2828 // If more events come in, there will be no more foreground window to send them to. This will
2829 // cause a cancel for the monitor, as well.
2830 ASSERT_EQ(InputEventInjectionResult::FAILED,
2831 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2832 ADISPLAY_ID_DEFAULT, {120, 200}))
2833 << "Injection should fail because the window was removed";
2834 window->assertNoEvents();
2835 // Global monitor now gets the cancel
2836 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2837}
2838
Michael Wright3a240c42019-12-10 20:53:41 +00002839// Tests for gesture monitors
2840TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002841 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002842 sp<FakeWindowHandle> window =
2843 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002844 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002845
chaviwd1c23182019-12-20 18:44:56 -08002846 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2847 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002848
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002852 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002853 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002854}
2855
2856TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002857 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002858 sp<FakeWindowHandle> window =
2859 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2860
2861 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002862 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002863
Arthur Hung72d8dc32020-03-28 00:48:39 +00002864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002865 setFocusedWindow(window);
2866
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002867 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002868
chaviwd1c23182019-12-20 18:44:56 -08002869 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2870 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002871
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2873 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002874 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002875 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002876}
2877
2878TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002879 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002880 sp<FakeWindowHandle> window =
2881 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002882 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002883
chaviwd1c23182019-12-20 18:44:56 -08002884 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2885 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002886
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002888 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002890 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002891 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002892
2893 window->releaseChannel();
2894
chaviwd1c23182019-12-20 18:44:56 -08002895 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002896
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002898 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002899 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002900 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002901}
2902
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002903TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2904 FakeMonitorReceiver monitor =
2905 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2906 true /*isGestureMonitor*/);
2907
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002909 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2910 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2911 ASSERT_TRUE(consumeSeq);
2912
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002913 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002914 monitor.finishEvent(*consumeSeq);
2915 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002916 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002917}
2918
Evan Rosky84f07f02021-04-16 10:42:42 -07002919// Tests for gesture monitors
2920TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2921 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2922 sp<FakeWindowHandle> window =
2923 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2924 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2925 window->setWindowOffset(20, 40);
2926 window->setWindowTransform(0, 1, -1, 0);
2927
2928 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2929 true /*isGestureMonitor*/);
2930
2931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2932 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2934 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2935 MotionEvent* event = monitor.consumeMotion();
2936 // Even though window has transform, gesture monitor must not.
2937 ASSERT_EQ(ui::Transform(), event->getTransform());
2938}
2939
Arthur Hungb3307ee2021-10-14 10:57:37 +00002940TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2941 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2942 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2943 true /*isGestureMonitor*/);
2944
2945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2948 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2949}
2950
chaviw81e2bb92019-12-18 15:03:51 -08002951TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002952 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002953 sp<FakeWindowHandle> window =
2954 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2955
Arthur Hung72d8dc32020-03-28 00:48:39 +00002956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002957
2958 NotifyMotionArgs motionArgs =
2959 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2960 ADISPLAY_ID_DEFAULT);
2961
2962 mDispatcher->notifyMotion(&motionArgs);
2963 // Window should receive motion down event.
2964 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2965
2966 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002967 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002968 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2969 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2970 motionArgs.pointerCoords[0].getX() - 10);
2971
2972 mDispatcher->notifyMotion(&motionArgs);
2973 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2974 0 /*expectedFlags*/);
2975}
2976
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002977/**
2978 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2979 * the device default right away. In the test scenario, we check both the default value,
2980 * and the action of enabling / disabling.
2981 */
2982TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002983 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002984 sp<FakeWindowHandle> window =
2985 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2986
2987 // Set focused application.
2988 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002989 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002990
2991 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002992 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002993 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002994 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2995
2996 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002997 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002999 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3000
3001 SCOPED_TRACE("Disable touch mode");
3002 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003003 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003004 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003006 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3008
3009 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003010 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3013
3014 SCOPED_TRACE("Enable touch mode again");
3015 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003016 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003017 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003019 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3021
3022 window->assertNoEvents();
3023}
3024
Gang Wange9087892020-01-07 12:17:14 -05003025TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003026 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003027 sp<FakeWindowHandle> window =
3028 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3029
3030 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003031 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003032
Arthur Hung72d8dc32020-03-28 00:48:39 +00003033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003034 setFocusedWindow(window);
3035
Gang Wange9087892020-01-07 12:17:14 -05003036 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3037
3038 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3039 mDispatcher->notifyKey(&keyArgs);
3040
3041 InputEvent* event = window->consume();
3042 ASSERT_NE(event, nullptr);
3043
3044 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3045 ASSERT_NE(verified, nullptr);
3046 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3047
3048 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3049 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3050 ASSERT_EQ(keyArgs.source, verified->source);
3051 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3052
3053 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3054
3055 ASSERT_EQ(keyArgs.action, verifiedKey.action);
3056 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003057 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
3058 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3059 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3060 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3061 ASSERT_EQ(0, verifiedKey.repeatCount);
3062}
3063
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003064TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003065 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003066 sp<FakeWindowHandle> window =
3067 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3068
3069 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3070
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003071 ui::Transform transform;
3072 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3073
3074 gui::DisplayInfo displayInfo;
3075 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3076 displayInfo.transform = transform;
3077
3078 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003079
3080 NotifyMotionArgs motionArgs =
3081 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3082 ADISPLAY_ID_DEFAULT);
3083 mDispatcher->notifyMotion(&motionArgs);
3084
3085 InputEvent* event = window->consume();
3086 ASSERT_NE(event, nullptr);
3087
3088 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3089 ASSERT_NE(verified, nullptr);
3090 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3091
3092 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3093 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3094 EXPECT_EQ(motionArgs.source, verified->source);
3095 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3096
3097 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3098
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003099 const vec2 rawXY =
3100 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3101 motionArgs.pointerCoords[0].getXYValue());
3102 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3103 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003104 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
3105 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
3106 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
3107 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3108 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3109}
3110
chaviw09c8d2d2020-08-24 15:48:26 -07003111/**
3112 * Ensure that separate calls to sign the same data are generating the same key.
3113 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3114 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3115 * tests.
3116 */
3117TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3118 KeyEvent event = getTestKeyEvent();
3119 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3120
3121 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3122 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3123 ASSERT_EQ(hmac1, hmac2);
3124}
3125
3126/**
3127 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3128 */
3129TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3130 KeyEvent event = getTestKeyEvent();
3131 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3132 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3133
3134 verifiedEvent.deviceId += 1;
3135 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3136
3137 verifiedEvent.source += 1;
3138 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3139
3140 verifiedEvent.eventTimeNanos += 1;
3141 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3142
3143 verifiedEvent.displayId += 1;
3144 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3145
3146 verifiedEvent.action += 1;
3147 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3148
3149 verifiedEvent.downTimeNanos += 1;
3150 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3151
3152 verifiedEvent.flags += 1;
3153 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3154
3155 verifiedEvent.keyCode += 1;
3156 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3157
3158 verifiedEvent.scanCode += 1;
3159 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3160
3161 verifiedEvent.metaState += 1;
3162 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3163
3164 verifiedEvent.repeatCount += 1;
3165 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3166}
3167
Vishnu Nair958da932020-08-21 17:12:37 -07003168TEST_F(InputDispatcherTest, SetFocusedWindow) {
3169 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3170 sp<FakeWindowHandle> windowTop =
3171 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3172 sp<FakeWindowHandle> windowSecond =
3173 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3174 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3175
3176 // Top window is also focusable but is not granted focus.
3177 windowTop->setFocusable(true);
3178 windowSecond->setFocusable(true);
3179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3180 setFocusedWindow(windowSecond);
3181
3182 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3184 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003185
3186 // Focused window should receive event.
3187 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3188 windowTop->assertNoEvents();
3189}
3190
3191TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3192 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3193 sp<FakeWindowHandle> window =
3194 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3195 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3196
3197 window->setFocusable(true);
3198 // Release channel for window is no longer valid.
3199 window->releaseChannel();
3200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3201 setFocusedWindow(window);
3202
3203 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003204 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3205 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003206
3207 // window channel is invalid, so it should not receive any input event.
3208 window->assertNoEvents();
3209}
3210
3211TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3213 sp<FakeWindowHandle> window =
3214 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3215 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3216
3217 // Window is not focusable.
3218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3219 setFocusedWindow(window);
3220
3221 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003222 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3223 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003224
3225 // window is invalid, so it should not receive any input event.
3226 window->assertNoEvents();
3227}
3228
3229TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3230 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3231 sp<FakeWindowHandle> windowTop =
3232 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3233 sp<FakeWindowHandle> windowSecond =
3234 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3235 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3236
3237 windowTop->setFocusable(true);
3238 windowSecond->setFocusable(true);
3239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3240 setFocusedWindow(windowTop);
3241 windowTop->consumeFocusEvent(true);
3242
3243 setFocusedWindow(windowSecond, windowTop);
3244 windowSecond->consumeFocusEvent(true);
3245 windowTop->consumeFocusEvent(false);
3246
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3248 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003249
3250 // Focused window should receive event.
3251 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3252}
3253
3254TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3255 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3256 sp<FakeWindowHandle> windowTop =
3257 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3258 sp<FakeWindowHandle> windowSecond =
3259 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3260 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3261
3262 windowTop->setFocusable(true);
3263 windowSecond->setFocusable(true);
3264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3265 setFocusedWindow(windowSecond, windowTop);
3266
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003267 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3268 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003269
3270 // Event should be dropped.
3271 windowTop->assertNoEvents();
3272 windowSecond->assertNoEvents();
3273}
3274
3275TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3276 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3277 sp<FakeWindowHandle> window =
3278 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3279 sp<FakeWindowHandle> previousFocusedWindow =
3280 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3281 ADISPLAY_ID_DEFAULT);
3282 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3283
3284 window->setFocusable(true);
3285 previousFocusedWindow->setFocusable(true);
3286 window->setVisible(false);
3287 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3288 setFocusedWindow(previousFocusedWindow);
3289 previousFocusedWindow->consumeFocusEvent(true);
3290
3291 // Requesting focus on invisible window takes focus from currently focused window.
3292 setFocusedWindow(window);
3293 previousFocusedWindow->consumeFocusEvent(false);
3294
3295 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003297 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003298 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003299
3300 // Window does not get focus event or key down.
3301 window->assertNoEvents();
3302
3303 // Window becomes visible.
3304 window->setVisible(true);
3305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3306
3307 // Window receives focus event.
3308 window->consumeFocusEvent(true);
3309 // Focused window receives key down.
3310 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3311}
3312
Vishnu Nair599f1412021-06-21 10:39:58 -07003313TEST_F(InputDispatcherTest, DisplayRemoved) {
3314 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3315 sp<FakeWindowHandle> window =
3316 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3317 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3318
3319 // window is granted focus.
3320 window->setFocusable(true);
3321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3322 setFocusedWindow(window);
3323 window->consumeFocusEvent(true);
3324
3325 // When a display is removed window loses focus.
3326 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3327 window->consumeFocusEvent(false);
3328}
3329
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003330/**
3331 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3332 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3333 * of the 'slipperyEnterWindow'.
3334 *
3335 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3336 * a way so that the touched location is no longer covered by the top window.
3337 *
3338 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3339 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3340 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3341 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3342 * with ACTION_DOWN).
3343 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3344 * window moved itself away from the touched location and had Flag::SLIPPERY.
3345 *
3346 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3347 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3348 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3349 *
3350 * In this test, we ensure that the event received by the bottom window has
3351 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3352 */
3353TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3354 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3355 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3356
3357 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3358 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3359
3360 sp<FakeWindowHandle> slipperyExitWindow =
3361 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003362 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003363 // Make sure this one overlaps the bottom window
3364 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3365 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3366 // one. Windows with the same owner are not considered to be occluding each other.
3367 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3368
3369 sp<FakeWindowHandle> slipperyEnterWindow =
3370 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3371 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3372
3373 mDispatcher->setInputWindows(
3374 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3375
3376 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3377 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3378 ADISPLAY_ID_DEFAULT, {{50, 50}});
3379 mDispatcher->notifyMotion(&args);
3380 slipperyExitWindow->consumeMotionDown();
3381 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3382 mDispatcher->setInputWindows(
3383 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3384
3385 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3386 ADISPLAY_ID_DEFAULT, {{51, 51}});
3387 mDispatcher->notifyMotion(&args);
3388
3389 slipperyExitWindow->consumeMotionCancel();
3390
3391 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3392 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3393}
3394
Garfield Tan1c7bc862020-01-28 13:24:04 -08003395class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3396protected:
3397 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3398 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3399
Chris Yea209fde2020-07-22 13:54:51 -07003400 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003401 sp<FakeWindowHandle> mWindow;
3402
3403 virtual void SetUp() override {
3404 mFakePolicy = new FakeInputDispatcherPolicy();
3405 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003406 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003407 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3408 ASSERT_EQ(OK, mDispatcher->start());
3409
3410 setUpWindow();
3411 }
3412
3413 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003414 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003415 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3416
Vishnu Nair47074b82020-08-14 11:54:47 -07003417 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003419 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003420 mWindow->consumeFocusEvent(true);
3421 }
3422
Chris Ye2ad95392020-09-01 13:44:44 -07003423 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003424 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003425 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003426 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3427 mDispatcher->notifyKey(&keyArgs);
3428
3429 // Window should receive key down event.
3430 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3431 }
3432
3433 void expectKeyRepeatOnce(int32_t repeatCount) {
3434 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3435 InputEvent* repeatEvent = mWindow->consume();
3436 ASSERT_NE(nullptr, repeatEvent);
3437
3438 uint32_t eventType = repeatEvent->getType();
3439 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3440
3441 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3442 uint32_t eventAction = repeatKeyEvent->getAction();
3443 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3444 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3445 }
3446
Chris Ye2ad95392020-09-01 13:44:44 -07003447 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003448 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003449 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003450 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3451 mDispatcher->notifyKey(&keyArgs);
3452
3453 // Window should receive key down event.
3454 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3455 0 /*expectedFlags*/);
3456 }
3457};
3458
3459TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003460 sendAndConsumeKeyDown(1 /* deviceId */);
3461 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3462 expectKeyRepeatOnce(repeatCount);
3463 }
3464}
3465
3466TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3467 sendAndConsumeKeyDown(1 /* deviceId */);
3468 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3469 expectKeyRepeatOnce(repeatCount);
3470 }
3471 sendAndConsumeKeyDown(2 /* deviceId */);
3472 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003473 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3474 expectKeyRepeatOnce(repeatCount);
3475 }
3476}
3477
3478TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003479 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003480 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003481 sendAndConsumeKeyUp(1 /* deviceId */);
3482 mWindow->assertNoEvents();
3483}
3484
3485TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3486 sendAndConsumeKeyDown(1 /* deviceId */);
3487 expectKeyRepeatOnce(1 /*repeatCount*/);
3488 sendAndConsumeKeyDown(2 /* deviceId */);
3489 expectKeyRepeatOnce(1 /*repeatCount*/);
3490 // Stale key up from device 1.
3491 sendAndConsumeKeyUp(1 /* deviceId */);
3492 // Device 2 is still down, keep repeating
3493 expectKeyRepeatOnce(2 /*repeatCount*/);
3494 expectKeyRepeatOnce(3 /*repeatCount*/);
3495 // Device 2 key up
3496 sendAndConsumeKeyUp(2 /* deviceId */);
3497 mWindow->assertNoEvents();
3498}
3499
3500TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3501 sendAndConsumeKeyDown(1 /* deviceId */);
3502 expectKeyRepeatOnce(1 /*repeatCount*/);
3503 sendAndConsumeKeyDown(2 /* deviceId */);
3504 expectKeyRepeatOnce(1 /*repeatCount*/);
3505 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3506 sendAndConsumeKeyUp(2 /* deviceId */);
3507 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003508 mWindow->assertNoEvents();
3509}
3510
liushenxiang42232912021-05-21 20:24:09 +08003511TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3512 sendAndConsumeKeyDown(DEVICE_ID);
3513 expectKeyRepeatOnce(1 /*repeatCount*/);
3514 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3515 mDispatcher->notifyDeviceReset(&args);
3516 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3517 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3518 mWindow->assertNoEvents();
3519}
3520
Garfield Tan1c7bc862020-01-28 13:24:04 -08003521TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003522 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003523 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3524 InputEvent* repeatEvent = mWindow->consume();
3525 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3526 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3527 IdGenerator::getSource(repeatEvent->getId()));
3528 }
3529}
3530
3531TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003532 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003533
3534 std::unordered_set<int32_t> idSet;
3535 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3536 InputEvent* repeatEvent = mWindow->consume();
3537 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3538 int32_t id = repeatEvent->getId();
3539 EXPECT_EQ(idSet.end(), idSet.find(id));
3540 idSet.insert(id);
3541 }
3542}
3543
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003544/* Test InputDispatcher for MultiDisplay */
3545class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3546public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003547 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003548 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003549
Chris Yea209fde2020-07-22 13:54:51 -07003550 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003551 windowInPrimary =
3552 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003553
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003554 // Set focus window for primary display, but focused display would be second one.
3555 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003556 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003558 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003559 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003560
Chris Yea209fde2020-07-22 13:54:51 -07003561 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003562 windowInSecondary =
3563 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003564 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003565 // Set focus display to second one.
3566 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3567 // Set focus window for second display.
3568 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003569 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003570 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003571 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003572 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003573 }
3574
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003575 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003576 InputDispatcherTest::TearDown();
3577
Chris Yea209fde2020-07-22 13:54:51 -07003578 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003580 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581 windowInSecondary.clear();
3582 }
3583
3584protected:
Chris Yea209fde2020-07-22 13:54:51 -07003585 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003586 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003587 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003588 sp<FakeWindowHandle> windowInSecondary;
3589};
3590
3591TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3592 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3595 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003596 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003597 windowInSecondary->assertNoEvents();
3598
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003603 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003604 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003605}
3606
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003607TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003608 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3610 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003611 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003612 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003613 windowInSecondary->assertNoEvents();
3614
3615 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003617 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003618 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003619 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003620
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003621 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003622 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003624 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003625 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3626 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003627
3628 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003629 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003630 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003631 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003632 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003633 windowInSecondary->assertNoEvents();
3634}
3635
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003636// Test per-display input monitors for motion event.
3637TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003638 FakeMonitorReceiver monitorInPrimary =
3639 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3640 FakeMonitorReceiver monitorInSecondary =
3641 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003642
3643 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3645 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003647 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003648 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003649 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003650 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003651
3652 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003656 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003657 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003658 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003659 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660
3661 // Test inject a non-pointer motion event.
3662 // If specific a display, it will dispatch to the focused window of particular display,
3663 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3665 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003668 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003669 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003670 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003671}
3672
3673// Test per-display input monitors for key event.
3674TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003675 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003676 FakeMonitorReceiver monitorInPrimary =
3677 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3678 FakeMonitorReceiver monitorInSecondary =
3679 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680
3681 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3683 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003685 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003686 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003687 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688}
3689
Vishnu Nair958da932020-08-21 17:12:37 -07003690TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3691 sp<FakeWindowHandle> secondWindowInPrimary =
3692 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3693 secondWindowInPrimary->setFocusable(true);
3694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3695 setFocusedWindow(secondWindowInPrimary);
3696 windowInPrimary->consumeFocusEvent(false);
3697 secondWindowInPrimary->consumeFocusEvent(true);
3698
3699 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3701 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003702 windowInPrimary->assertNoEvents();
3703 windowInSecondary->assertNoEvents();
3704 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3705}
3706
Jackal Guof9696682018-10-05 12:23:23 +08003707class InputFilterTest : public InputDispatcherTest {
3708protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003709 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3710 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003711 NotifyMotionArgs motionArgs;
3712
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003713 motionArgs =
3714 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003715 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003716 motionArgs =
3717 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003718 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003719 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003720 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003721 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3722 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003723 } else {
3724 mFakePolicy->assertFilterInputEventWasNotCalled();
3725 }
3726 }
3727
3728 void testNotifyKey(bool expectToBeFiltered) {
3729 NotifyKeyArgs keyArgs;
3730
3731 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3732 mDispatcher->notifyKey(&keyArgs);
3733 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3734 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003735 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003736
3737 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003738 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003739 } else {
3740 mFakePolicy->assertFilterInputEventWasNotCalled();
3741 }
3742 }
3743};
3744
3745// Test InputFilter for MotionEvent
3746TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3747 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3748 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3749 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3750
3751 // Enable InputFilter
3752 mDispatcher->setInputFilterEnabled(true);
3753 // Test touch on both primary and second display, and check if both events are filtered.
3754 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3755 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3756
3757 // Disable InputFilter
3758 mDispatcher->setInputFilterEnabled(false);
3759 // Test touch on both primary and second display, and check if both events aren't filtered.
3760 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3761 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3762}
3763
3764// Test InputFilter for KeyEvent
3765TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3766 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3767 testNotifyKey(/*expectToBeFiltered*/ false);
3768
3769 // Enable InputFilter
3770 mDispatcher->setInputFilterEnabled(true);
3771 // Send a key event, and check if it is filtered.
3772 testNotifyKey(/*expectToBeFiltered*/ true);
3773
3774 // Disable InputFilter
3775 mDispatcher->setInputFilterEnabled(false);
3776 // Send a key event, and check if it isn't filtered.
3777 testNotifyKey(/*expectToBeFiltered*/ false);
3778}
3779
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003780// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3781// logical display coordinate space.
3782TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3783 ui::Transform firstDisplayTransform;
3784 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3785 ui::Transform secondDisplayTransform;
3786 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3787
3788 std::vector<gui::DisplayInfo> displayInfos(2);
3789 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3790 displayInfos[0].transform = firstDisplayTransform;
3791 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3792 displayInfos[1].transform = secondDisplayTransform;
3793
3794 mDispatcher->onWindowInfosChanged({}, displayInfos);
3795
3796 // Enable InputFilter
3797 mDispatcher->setInputFilterEnabled(true);
3798
3799 // Ensure the correct transforms are used for the displays.
3800 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3801 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3802}
3803
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003804class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3805protected:
3806 virtual void SetUp() override {
3807 InputDispatcherTest::SetUp();
3808
3809 /**
3810 * We don't need to enable input filter to test the injected event policy, but we enabled it
3811 * here to make the tests more realistic, since this policy only matters when inputfilter is
3812 * on.
3813 */
3814 mDispatcher->setInputFilterEnabled(true);
3815
3816 std::shared_ptr<InputApplicationHandle> application =
3817 std::make_shared<FakeApplicationHandle>();
3818 mWindow =
3819 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3820
3821 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3822 mWindow->setFocusable(true);
3823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3824 setFocusedWindow(mWindow);
3825 mWindow->consumeFocusEvent(true);
3826 }
3827
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003828 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3829 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003830 KeyEvent event;
3831
3832 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3833 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3834 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3835 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3836 const int32_t additionalPolicyFlags =
3837 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3838 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3839 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3840 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3841 policyFlags | additionalPolicyFlags));
3842
3843 InputEvent* received = mWindow->consume();
3844 ASSERT_NE(nullptr, received);
3845 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003846 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3847 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3848 ASSERT_EQ(flags, keyEvent.getFlags());
3849 }
3850
3851 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3852 int32_t flags) {
3853 MotionEvent event;
3854 PointerProperties pointerProperties[1];
3855 PointerCoords pointerCoords[1];
3856 pointerProperties[0].clear();
3857 pointerProperties[0].id = 0;
3858 pointerCoords[0].clear();
3859 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3860 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3861
3862 ui::Transform identityTransform;
3863 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3864 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3865 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3866 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3867 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003868 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003869 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003870 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3871
3872 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3873 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3874 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3875 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3876 policyFlags | additionalPolicyFlags));
3877
3878 InputEvent* received = mWindow->consume();
3879 ASSERT_NE(nullptr, received);
3880 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3881 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3882 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3883 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003884 }
3885
3886private:
3887 sp<FakeWindowHandle> mWindow;
3888};
3889
3890TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003891 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3892 // filter. Without it, the event will no different from a regularly injected event, and the
3893 // injected device id will be overwritten.
3894 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3895 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003896}
3897
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003898TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003899 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003900 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3901 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3902}
3903
3904TEST_F(InputFilterInjectionPolicyTest,
3905 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3906 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3907 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3908 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003909}
3910
3911TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3912 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003913 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003914}
3915
chaviwfd6d3512019-03-25 13:23:49 -07003916class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003917 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003918 InputDispatcherTest::SetUp();
3919
Chris Yea209fde2020-07-22 13:54:51 -07003920 std::shared_ptr<FakeApplicationHandle> application =
3921 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003922 mUnfocusedWindow =
3923 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003924 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3925 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3926 // window.
chaviw3277faf2021-05-19 16:45:23 -05003927 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003928
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003929 mFocusedWindow =
3930 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3931 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003932 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003933
3934 // Set focused application.
3935 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003936 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003937
3938 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003940 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003941 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003942 }
3943
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003944 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003945 InputDispatcherTest::TearDown();
3946
3947 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003948 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003949 }
3950
3951protected:
3952 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003953 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003954 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003955};
3956
3957// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3958// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3959// the onPointerDownOutsideFocus callback.
3960TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003962 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3963 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003965 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003966
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003967 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003968 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3969}
3970
3971// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3972// DOWN on the window that doesn't have focus. Ensure no window received the
3973// onPointerDownOutsideFocus callback.
3974TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003976 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003978 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003979
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003980 ASSERT_TRUE(mDispatcher->waitForIdle());
3981 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003982}
3983
3984// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3985// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3986TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3988 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003990 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003991
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003992 ASSERT_TRUE(mDispatcher->waitForIdle());
3993 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003994}
3995
3996// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3997// DOWN on the window that already has focus. Ensure no window received the
3998// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003999TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004001 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004002 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004003 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004004 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004005
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004006 ASSERT_TRUE(mDispatcher->waitForIdle());
4007 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004008}
4009
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004010// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4011// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4012TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4013 const MotionEvent event =
4014 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4015 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4016 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4017 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4018 .build();
4019 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4021 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4022
4023 ASSERT_TRUE(mDispatcher->waitForIdle());
4024 mFakePolicy->assertOnPointerDownWasNotCalled();
4025 // Ensure that the unfocused window did not receive any FOCUS events.
4026 mUnfocusedWindow->assertNoEvents();
4027}
4028
chaviwaf87b3e2019-10-01 16:59:28 -07004029// These tests ensures we can send touch events to a single client when there are multiple input
4030// windows that point to the same client token.
4031class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4032 virtual void SetUp() override {
4033 InputDispatcherTest::SetUp();
4034
Chris Yea209fde2020-07-22 13:54:51 -07004035 std::shared_ptr<FakeApplicationHandle> application =
4036 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004037 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4038 ADISPLAY_ID_DEFAULT);
4039 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4040 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004041 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004042 mWindow1->setFrame(Rect(0, 0, 100, 100));
4043
4044 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4045 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004046 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004047 mWindow2->setFrame(Rect(100, 100, 200, 200));
4048
Arthur Hung72d8dc32020-03-28 00:48:39 +00004049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004050 }
4051
4052protected:
4053 sp<FakeWindowHandle> mWindow1;
4054 sp<FakeWindowHandle> mWindow2;
4055
4056 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004057 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004058 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4059 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004060 }
4061
4062 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4063 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004064 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004065 InputEvent* event = window->consume();
4066
4067 ASSERT_NE(nullptr, event) << name.c_str()
4068 << ": consumer should have returned non-NULL event.";
4069
4070 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4071 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4072 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4073
4074 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004075 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004076
4077 for (size_t i = 0; i < points.size(); i++) {
4078 float expectedX = points[i].x;
4079 float expectedY = points[i].y;
4080
4081 EXPECT_EQ(expectedX, motionEvent.getX(i))
4082 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4083 << ", got " << motionEvent.getX(i);
4084 EXPECT_EQ(expectedY, motionEvent.getY(i))
4085 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4086 << ", got " << motionEvent.getY(i);
4087 }
4088 }
chaviw9eaa22c2020-07-01 16:21:27 -07004089
4090 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
4091 std::vector<PointF> expectedPoints) {
4092 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4093 ADISPLAY_ID_DEFAULT, touchedPoints);
4094 mDispatcher->notifyMotion(&motionArgs);
4095
4096 // Always consume from window1 since it's the window that has the InputReceiver
4097 consumeMotionEvent(mWindow1, action, expectedPoints);
4098 }
chaviwaf87b3e2019-10-01 16:59:28 -07004099};
4100
4101TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4102 // Touch Window 1
4103 PointF touchedPoint = {10, 10};
4104 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004105 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004106
4107 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004108 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004109
4110 // Touch Window 2
4111 touchedPoint = {150, 150};
4112 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004113 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004114}
4115
chaviw9eaa22c2020-07-01 16:21:27 -07004116TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4117 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004118 mWindow2->setWindowScale(0.5f, 0.5f);
4119
4120 // Touch Window 1
4121 PointF touchedPoint = {10, 10};
4122 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004123 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004124 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004125 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004126
4127 // Touch Window 2
4128 touchedPoint = {150, 150};
4129 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004130 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4131 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004132
chaviw9eaa22c2020-07-01 16:21:27 -07004133 // Update the transform so rotation is set
4134 mWindow2->setWindowTransform(0, -1, 1, 0);
4135 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4136 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004137}
4138
chaviw9eaa22c2020-07-01 16:21:27 -07004139TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004140 mWindow2->setWindowScale(0.5f, 0.5f);
4141
4142 // Touch Window 1
4143 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4144 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004145 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004146
4147 // Touch Window 2
4148 int32_t actionPointerDown =
4149 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004150 touchedPoints.push_back(PointF{150, 150});
4151 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4152 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004153
chaviw9eaa22c2020-07-01 16:21:27 -07004154 // Release Window 2
4155 int32_t actionPointerUp =
4156 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4157 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4158 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004159
chaviw9eaa22c2020-07-01 16:21:27 -07004160 // Update the transform so rotation is set for Window 2
4161 mWindow2->setWindowTransform(0, -1, 1, 0);
4162 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4163 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004164}
4165
chaviw9eaa22c2020-07-01 16:21:27 -07004166TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004167 mWindow2->setWindowScale(0.5f, 0.5f);
4168
4169 // Touch Window 1
4170 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4171 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004172 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004173
4174 // Touch Window 2
4175 int32_t actionPointerDown =
4176 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004177 touchedPoints.push_back(PointF{150, 150});
4178 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004179
chaviw9eaa22c2020-07-01 16:21:27 -07004180 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004181
4182 // Move both windows
4183 touchedPoints = {{20, 20}, {175, 175}};
4184 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4185 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4186
chaviw9eaa22c2020-07-01 16:21:27 -07004187 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004188
chaviw9eaa22c2020-07-01 16:21:27 -07004189 // Release Window 2
4190 int32_t actionPointerUp =
4191 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4192 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4193 expectedPoints.pop_back();
4194
4195 // Touch Window 2
4196 mWindow2->setWindowTransform(0, -1, 1, 0);
4197 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4198 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4199
4200 // Move both windows
4201 touchedPoints = {{20, 20}, {175, 175}};
4202 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4203 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4204
4205 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004206}
4207
4208TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4209 mWindow1->setWindowScale(0.5f, 0.5f);
4210
4211 // Touch Window 1
4212 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4213 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004214 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004215
4216 // Touch Window 2
4217 int32_t actionPointerDown =
4218 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004219 touchedPoints.push_back(PointF{150, 150});
4220 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004221
chaviw9eaa22c2020-07-01 16:21:27 -07004222 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004223
4224 // Move both windows
4225 touchedPoints = {{20, 20}, {175, 175}};
4226 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4227 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4228
chaviw9eaa22c2020-07-01 16:21:27 -07004229 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004230}
4231
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004232class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4233 virtual void SetUp() override {
4234 InputDispatcherTest::SetUp();
4235
Chris Yea209fde2020-07-22 13:54:51 -07004236 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004237 mApplication->setDispatchingTimeout(20ms);
4238 mWindow =
4239 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4240 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004241 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004242 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004243 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4244 // window.
chaviw3277faf2021-05-19 16:45:23 -05004245 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004246
4247 // Set focused application.
4248 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4249
4250 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004251 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004252 mWindow->consumeFocusEvent(true);
4253 }
4254
4255 virtual void TearDown() override {
4256 InputDispatcherTest::TearDown();
4257 mWindow.clear();
4258 }
4259
4260protected:
Chris Yea209fde2020-07-22 13:54:51 -07004261 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004262 sp<FakeWindowHandle> mWindow;
4263 static constexpr PointF WINDOW_LOCATION = {20, 20};
4264
4265 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004267 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4268 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004270 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4271 WINDOW_LOCATION));
4272 }
4273};
4274
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004275// Send a tap and respond, which should not cause an ANR.
4276TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4277 tapOnWindow();
4278 mWindow->consumeMotionDown();
4279 mWindow->consumeMotionUp();
4280 ASSERT_TRUE(mDispatcher->waitForIdle());
4281 mFakePolicy->assertNotifyAnrWasNotCalled();
4282}
4283
4284// Send a regular key and respond, which should not cause an ANR.
4285TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004287 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4288 ASSERT_TRUE(mDispatcher->waitForIdle());
4289 mFakePolicy->assertNotifyAnrWasNotCalled();
4290}
4291
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004292TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4293 mWindow->setFocusable(false);
4294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4295 mWindow->consumeFocusEvent(false);
4296
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004297 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004298 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004299 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4300 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004302 // Key will not go to window because we have no focused window.
4303 // The 'no focused window' ANR timer should start instead.
4304
4305 // Now, the focused application goes away.
4306 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4307 // The key should get dropped and there should be no ANR.
4308
4309 ASSERT_TRUE(mDispatcher->waitForIdle());
4310 mFakePolicy->assertNotifyAnrWasNotCalled();
4311}
4312
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004313// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004314// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4315// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004316TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004318 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4319 WINDOW_LOCATION));
4320
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004321 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4322 ASSERT_TRUE(sequenceNum);
4323 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004324 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004325
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004326 mWindow->finishEvent(*sequenceNum);
4327 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4328 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004329 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004330 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004331}
4332
4333// Send a key to the app and have the app not respond right away.
4334TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4335 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004337 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4338 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004339 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004340 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004341 ASSERT_TRUE(mDispatcher->waitForIdle());
4342}
4343
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344// We have a focused application, but no focused window
4345TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004346 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4348 mWindow->consumeFocusEvent(false);
4349
4350 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004352 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4353 WINDOW_LOCATION));
4354 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4355 mDispatcher->waitForIdle();
4356 mFakePolicy->assertNotifyAnrWasNotCalled();
4357
4358 // Once a focused event arrives, we get an ANR for this application
4359 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4360 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004361 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004363 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004365 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004366 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004367 ASSERT_TRUE(mDispatcher->waitForIdle());
4368}
4369
4370// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004371// Make sure that we don't notify policy twice about the same ANR.
4372TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004373 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4375 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004376
4377 // Once a focused event arrives, we get an ANR for this application
4378 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4379 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004380 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004381 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004382 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004384 const std::chrono::duration appTimeout =
4385 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004386 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004388 std::this_thread::sleep_for(appTimeout);
4389 // ANR should not be raised again. It is up to policy to do that if it desires.
4390 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004391
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004392 // If we now get a focused window, the ANR should stop, but the policy handles that via
4393 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394 ASSERT_TRUE(mDispatcher->waitForIdle());
4395}
4396
4397// We have a focused application, but no focused window
4398TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004399 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4401 mWindow->consumeFocusEvent(false);
4402
4403 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004404 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004405 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4407 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004408
4409 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004410 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004411
4412 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004413 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004414 ASSERT_TRUE(mDispatcher->waitForIdle());
4415 mWindow->assertNoEvents();
4416}
4417
4418/**
4419 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4420 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4421 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4422 * the ANR mechanism should still work.
4423 *
4424 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4425 * DOWN event, while not responding on the second one.
4426 */
4427TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4428 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4429 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4430 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4431 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4432 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004433 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434
4435 // Now send ACTION_UP, with identical timestamp
4436 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4437 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4438 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4439 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004440 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004441
4442 // We have now sent down and up. Let's consume first event and then ANR on the second.
4443 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4444 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004445 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446}
4447
4448// If an app is not responding to a key event, gesture monitors should continue to receive
4449// new motion events
4450TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4451 FakeMonitorReceiver monitor =
4452 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4453 true /*isGestureMonitor*/);
4454
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4456 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459
4460 // Stuck on the ACTION_UP
4461 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004462 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004463
4464 // New tap will go to the gesture monitor, but not to the window
4465 tapOnWindow();
4466 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4467 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4468
4469 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4470 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004471 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472 mWindow->assertNoEvents();
4473 monitor.assertNoEvents();
4474}
4475
4476// If an app is not responding to a motion event, gesture monitors should continue to receive
4477// new motion events
4478TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4479 FakeMonitorReceiver monitor =
4480 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4481 true /*isGestureMonitor*/);
4482
4483 tapOnWindow();
4484 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4485 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4486
4487 mWindow->consumeMotionDown();
4488 // Stuck on the ACTION_UP
4489 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004490 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004491
4492 // New tap will go to the gesture monitor, but not to the window
4493 tapOnWindow();
4494 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4495 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4496
4497 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4498 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004499 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500 mWindow->assertNoEvents();
4501 monitor.assertNoEvents();
4502}
4503
4504// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4505// process events, you don't get an anr. When the window later becomes unresponsive again, you
4506// get an ANR again.
4507// 1. tap -> block on ACTION_UP -> receive ANR
4508// 2. consume all pending events (= queue becomes healthy again)
4509// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4510TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4511 tapOnWindow();
4512
4513 mWindow->consumeMotionDown();
4514 // Block on ACTION_UP
4515 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004516 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004517 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4518 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004519 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520 mWindow->assertNoEvents();
4521
4522 tapOnWindow();
4523 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004524 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004525 mWindow->consumeMotionUp();
4526
4527 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004528 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004529 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004530 mWindow->assertNoEvents();
4531}
4532
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004533// If a connection remains unresponsive for a while, make sure policy is only notified once about
4534// it.
4535TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4538 WINDOW_LOCATION));
4539
4540 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004541 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004543 // 'notifyConnectionUnresponsive' should only be called once per connection
4544 mFakePolicy->assertNotifyAnrWasNotCalled();
4545 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546 mWindow->consumeMotionDown();
4547 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4548 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4549 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004550 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004551 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004552 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553}
4554
4555/**
4556 * If a window is processing a motion event, and then a key event comes in, the key event should
4557 * not to to the focused window until the motion is processed.
4558 *
4559 * Warning!!!
4560 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4561 * and the injection timeout that we specify when injecting the key.
4562 * We must have the injection timeout (10ms) be smaller than
4563 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4564 *
4565 * If that value changes, this test should also change.
4566 */
4567TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4568 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4570
4571 tapOnWindow();
4572 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4573 ASSERT_TRUE(downSequenceNum);
4574 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4575 ASSERT_TRUE(upSequenceNum);
4576 // Don't finish the events yet, and send a key
4577 // Injection will "succeed" because we will eventually give up and send the key to the focused
4578 // window even if motions are still being processed. But because the injection timeout is short,
4579 // we will receive INJECTION_TIMED_OUT as the result.
4580
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004581 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004582 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4584 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585 // Key will not be sent to the window, yet, because the window is still processing events
4586 // and the key remains pending, waiting for the touch events to be processed
4587 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4588 ASSERT_FALSE(keySequenceNum);
4589
4590 std::this_thread::sleep_for(500ms);
4591 // if we wait long enough though, dispatcher will give up, and still send the key
4592 // to the focused window, even though we have not yet finished the motion event
4593 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4594 mWindow->finishEvent(*downSequenceNum);
4595 mWindow->finishEvent(*upSequenceNum);
4596}
4597
4598/**
4599 * If a window is processing a motion event, and then a key event comes in, the key event should
4600 * not go to the focused window until the motion is processed.
4601 * If then a new motion comes in, then the pending key event should be going to the currently
4602 * focused window right away.
4603 */
4604TEST_F(InputDispatcherSingleWindowAnr,
4605 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4606 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4608
4609 tapOnWindow();
4610 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4611 ASSERT_TRUE(downSequenceNum);
4612 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4613 ASSERT_TRUE(upSequenceNum);
4614 // Don't finish the events yet, and send a key
4615 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004618 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004619 // At this point, key is still pending, and should not be sent to the application yet.
4620 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4621 ASSERT_FALSE(keySequenceNum);
4622
4623 // Now tap down again. It should cause the pending key to go to the focused window right away.
4624 tapOnWindow();
4625 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4626 // the other events yet. We can finish events in any order.
4627 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4628 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4629 mWindow->consumeMotionDown();
4630 mWindow->consumeMotionUp();
4631 mWindow->assertNoEvents();
4632}
4633
4634class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4635 virtual void SetUp() override {
4636 InputDispatcherTest::SetUp();
4637
Chris Yea209fde2020-07-22 13:54:51 -07004638 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004639 mApplication->setDispatchingTimeout(10ms);
4640 mUnfocusedWindow =
4641 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4642 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4643 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4644 // window.
4645 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004646 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4647 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4648 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649
4650 mFocusedWindow =
4651 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004652 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004654 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655
4656 // Set focused application.
4657 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004658 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004659
4660 // Expect one focus window exist in display.
4661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004662 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663 mFocusedWindow->consumeFocusEvent(true);
4664 }
4665
4666 virtual void TearDown() override {
4667 InputDispatcherTest::TearDown();
4668
4669 mUnfocusedWindow.clear();
4670 mFocusedWindow.clear();
4671 }
4672
4673protected:
Chris Yea209fde2020-07-22 13:54:51 -07004674 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 sp<FakeWindowHandle> mUnfocusedWindow;
4676 sp<FakeWindowHandle> mFocusedWindow;
4677 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4678 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4679 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4680
4681 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4682
4683 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4684
4685private:
4686 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4689 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004691 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4692 location));
4693 }
4694};
4695
4696// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4697// should be ANR'd first.
4698TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4701 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 mFocusedWindow->consumeMotionDown();
4704 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4705 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4706 // We consumed all events, so no ANR
4707 ASSERT_TRUE(mDispatcher->waitForIdle());
4708 mFakePolicy->assertNotifyAnrWasNotCalled();
4709
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004711 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4712 FOCUSED_WINDOW_LOCATION));
4713 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4714 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004715
4716 const std::chrono::duration timeout =
4717 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004718 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004719 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4720 // sequence to make it consistent
4721 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004723 mFocusedWindow->consumeMotionDown();
4724 // This cancel is generated because the connection was unresponsive
4725 mFocusedWindow->consumeMotionCancel();
4726 mFocusedWindow->assertNoEvents();
4727 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004729 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004730 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731}
4732
4733// If we have 2 windows with identical timeouts that are both unresponsive,
4734// it doesn't matter which order they should have ANR.
4735// But we should receive ANR for both.
4736TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4737 // Set the timeout for unfocused window to match the focused window
4738 mUnfocusedWindow->setDispatchingTimeout(10ms);
4739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4740
4741 tapOnFocusedWindow();
4742 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004743 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4744 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745
4746 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004747 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4748 mFocusedWindow->getToken() == anrConnectionToken2);
4749 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4750 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004751
4752 ASSERT_TRUE(mDispatcher->waitForIdle());
4753 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004754
4755 mFocusedWindow->consumeMotionDown();
4756 mFocusedWindow->consumeMotionUp();
4757 mUnfocusedWindow->consumeMotionOutside();
4758
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004759 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4760 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004761
4762 // Both applications should be marked as responsive, in any order
4763 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4764 mFocusedWindow->getToken() == responsiveToken2);
4765 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4766 mUnfocusedWindow->getToken() == responsiveToken2);
4767 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768}
4769
4770// If a window is already not responding, the second tap on the same window should be ignored.
4771// We should also log an error to account for the dropped event (not tested here).
4772// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4773TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4774 tapOnFocusedWindow();
4775 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4776 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4777 // Receive the events, but don't respond
4778 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4779 ASSERT_TRUE(downEventSequenceNum);
4780 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4781 ASSERT_TRUE(upEventSequenceNum);
4782 const std::chrono::duration timeout =
4783 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004784 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785
4786 // Tap once again
4787 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4790 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4793 FOCUSED_WINDOW_LOCATION));
4794 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4795 // valid touch target
4796 mUnfocusedWindow->assertNoEvents();
4797
4798 // Consume the first tap
4799 mFocusedWindow->finishEvent(*downEventSequenceNum);
4800 mFocusedWindow->finishEvent(*upEventSequenceNum);
4801 ASSERT_TRUE(mDispatcher->waitForIdle());
4802 // The second tap did not go to the focused window
4803 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004804 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004805 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 mFakePolicy->assertNotifyAnrWasNotCalled();
4807}
4808
4809// If you tap outside of all windows, there will not be ANR
4810TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4813 LOCATION_OUTSIDE_ALL_WINDOWS));
4814 ASSERT_TRUE(mDispatcher->waitForIdle());
4815 mFakePolicy->assertNotifyAnrWasNotCalled();
4816}
4817
4818// Since the focused window is paused, tapping on it should not produce any events
4819TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4820 mFocusedWindow->setPaused(true);
4821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4822
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4825 FOCUSED_WINDOW_LOCATION));
4826
4827 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4828 ASSERT_TRUE(mDispatcher->waitForIdle());
4829 // Should not ANR because the window is paused, and touches shouldn't go to it
4830 mFakePolicy->assertNotifyAnrWasNotCalled();
4831
4832 mFocusedWindow->assertNoEvents();
4833 mUnfocusedWindow->assertNoEvents();
4834}
4835
4836/**
4837 * If a window is processing a motion event, and then a key event comes in, the key event should
4838 * not to to the focused window until the motion is processed.
4839 * If a different window becomes focused at this time, the key should go to that window instead.
4840 *
4841 * Warning!!!
4842 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4843 * and the injection timeout that we specify when injecting the key.
4844 * We must have the injection timeout (10ms) be smaller than
4845 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4846 *
4847 * If that value changes, this test should also change.
4848 */
4849TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4850 // Set a long ANR timeout to prevent it from triggering
4851 mFocusedWindow->setDispatchingTimeout(2s);
4852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4853
4854 tapOnUnfocusedWindow();
4855 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4856 ASSERT_TRUE(downSequenceNum);
4857 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4858 ASSERT_TRUE(upSequenceNum);
4859 // Don't finish the events yet, and send a key
4860 // Injection will succeed because we will eventually give up and send the key to the focused
4861 // window even if motions are still being processed.
4862
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004863 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867 // Key will not be sent to the window, yet, because the window is still processing events
4868 // and the key remains pending, waiting for the touch events to be processed
4869 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4870 ASSERT_FALSE(keySequenceNum);
4871
4872 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004873 mFocusedWindow->setFocusable(false);
4874 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004876 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877
4878 // Focus events should precede the key events
4879 mUnfocusedWindow->consumeFocusEvent(true);
4880 mFocusedWindow->consumeFocusEvent(false);
4881
4882 // Finish the tap events, which should unblock dispatcher
4883 mUnfocusedWindow->finishEvent(*downSequenceNum);
4884 mUnfocusedWindow->finishEvent(*upSequenceNum);
4885
4886 // Now that all queues are cleared and no backlog in the connections, the key event
4887 // can finally go to the newly focused "mUnfocusedWindow".
4888 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4889 mFocusedWindow->assertNoEvents();
4890 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004891 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004892}
4893
4894// When the touch stream is split across 2 windows, and one of them does not respond,
4895// then ANR should be raised and the touch should be canceled for the unresponsive window.
4896// The other window should not be affected by that.
4897TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4898 // Touch Window 1
4899 NotifyMotionArgs motionArgs =
4900 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4901 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4902 mDispatcher->notifyMotion(&motionArgs);
4903 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4904 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4905
4906 // Touch Window 2
4907 int32_t actionPointerDown =
4908 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4909
4910 motionArgs =
4911 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4912 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4913 mDispatcher->notifyMotion(&motionArgs);
4914
4915 const std::chrono::duration timeout =
4916 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004917 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918
4919 mUnfocusedWindow->consumeMotionDown();
4920 mFocusedWindow->consumeMotionDown();
4921 // Focused window may or may not receive ACTION_MOVE
4922 // But it should definitely receive ACTION_CANCEL due to the ANR
4923 InputEvent* event;
4924 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4925 ASSERT_TRUE(moveOrCancelSequenceNum);
4926 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4927 ASSERT_NE(nullptr, event);
4928 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4929 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4930 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4931 mFocusedWindow->consumeMotionCancel();
4932 } else {
4933 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4934 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004936 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004937
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004938 mUnfocusedWindow->assertNoEvents();
4939 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004940 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941}
4942
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004943/**
4944 * If we have no focused window, and a key comes in, we start the ANR timer.
4945 * The focused application should add a focused window before the timer runs out to prevent ANR.
4946 *
4947 * If the user touches another application during this time, the key should be dropped.
4948 * Next, if a new focused window comes in, without toggling the focused application,
4949 * then no ANR should occur.
4950 *
4951 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4952 * but in some cases the policy may not update the focused application.
4953 */
4954TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4955 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4956 std::make_shared<FakeApplicationHandle>();
4957 focusedApplication->setDispatchingTimeout(60ms);
4958 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4959 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4960 mFocusedWindow->setFocusable(false);
4961
4962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4963 mFocusedWindow->consumeFocusEvent(false);
4964
4965 // Send a key. The ANR timer should start because there is no focused window.
4966 // 'focusedApplication' will get blamed if this timer completes.
4967 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004968 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004969 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004970 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4971 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004973
4974 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4975 // then the injected touches won't cause the focused event to get dropped.
4976 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4977 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4978 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4979 // For this test, it means that the key would get delivered to the window once it becomes
4980 // focused.
4981 std::this_thread::sleep_for(10ms);
4982
4983 // Touch unfocused window. This should force the pending key to get dropped.
4984 NotifyMotionArgs motionArgs =
4985 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4986 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4987 mDispatcher->notifyMotion(&motionArgs);
4988
4989 // We do not consume the motion right away, because that would require dispatcher to first
4990 // process (== drop) the key event, and by that time, ANR will be raised.
4991 // Set the focused window first.
4992 mFocusedWindow->setFocusable(true);
4993 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4994 setFocusedWindow(mFocusedWindow);
4995 mFocusedWindow->consumeFocusEvent(true);
4996 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4997 // to another application. This could be a bug / behaviour in the policy.
4998
4999 mUnfocusedWindow->consumeMotionDown();
5000
5001 ASSERT_TRUE(mDispatcher->waitForIdle());
5002 // Should not ANR because we actually have a focused window. It was just added too slowly.
5003 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5004}
5005
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005006// These tests ensure we cannot send touch events to a window that's positioned behind a window
5007// that has feature NO_INPUT_CHANNEL.
5008// Layout:
5009// Top (closest to user)
5010// mNoInputWindow (above all windows)
5011// mBottomWindow
5012// Bottom (furthest from user)
5013class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5014 virtual void SetUp() override {
5015 InputDispatcherTest::SetUp();
5016
5017 mApplication = std::make_shared<FakeApplicationHandle>();
5018 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5019 "Window without input channel", ADISPLAY_ID_DEFAULT,
5020 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5021
chaviw3277faf2021-05-19 16:45:23 -05005022 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005023 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5024 // It's perfectly valid for this window to not have an associated input channel
5025
5026 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5027 ADISPLAY_ID_DEFAULT);
5028 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5029
5030 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5031 }
5032
5033protected:
5034 std::shared_ptr<FakeApplicationHandle> mApplication;
5035 sp<FakeWindowHandle> mNoInputWindow;
5036 sp<FakeWindowHandle> mBottomWindow;
5037};
5038
5039TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5040 PointF touchedPoint = {10, 10};
5041
5042 NotifyMotionArgs motionArgs =
5043 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5044 ADISPLAY_ID_DEFAULT, {touchedPoint});
5045 mDispatcher->notifyMotion(&motionArgs);
5046
5047 mNoInputWindow->assertNoEvents();
5048 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5049 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5050 // and therefore should prevent mBottomWindow from receiving touches
5051 mBottomWindow->assertNoEvents();
5052}
5053
5054/**
5055 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5056 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5057 */
5058TEST_F(InputDispatcherMultiWindowOcclusionTests,
5059 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5060 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5061 "Window with input channel and NO_INPUT_CHANNEL",
5062 ADISPLAY_ID_DEFAULT);
5063
chaviw3277faf2021-05-19 16:45:23 -05005064 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005065 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5066 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5067
5068 PointF touchedPoint = {10, 10};
5069
5070 NotifyMotionArgs motionArgs =
5071 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5072 ADISPLAY_ID_DEFAULT, {touchedPoint});
5073 mDispatcher->notifyMotion(&motionArgs);
5074
5075 mNoInputWindow->assertNoEvents();
5076 mBottomWindow->assertNoEvents();
5077}
5078
Vishnu Nair958da932020-08-21 17:12:37 -07005079class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5080protected:
5081 std::shared_ptr<FakeApplicationHandle> mApp;
5082 sp<FakeWindowHandle> mWindow;
5083 sp<FakeWindowHandle> mMirror;
5084
5085 virtual void SetUp() override {
5086 InputDispatcherTest::SetUp();
5087 mApp = std::make_shared<FakeApplicationHandle>();
5088 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5089 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5090 mWindow->getToken());
5091 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5092 mWindow->setFocusable(true);
5093 mMirror->setFocusable(true);
5094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5095 }
5096};
5097
5098TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5099 // Request focus on a mirrored window
5100 setFocusedWindow(mMirror);
5101
5102 // window gets focused
5103 mWindow->consumeFocusEvent(true);
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);
5107}
5108
5109// A focused & mirrored window remains focused only if the window and its mirror are both
5110// focusable.
5111TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5112 setFocusedWindow(mMirror);
5113
5114 // window gets focused
5115 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5117 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005118 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5120 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005121 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5122
5123 mMirror->setFocusable(false);
5124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5125
5126 // window loses focus since one of the windows associated with the token in not focusable
5127 mWindow->consumeFocusEvent(false);
5128
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005129 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5130 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005131 mWindow->assertNoEvents();
5132}
5133
5134// A focused & mirrored window remains focused until the window and its mirror both become
5135// invisible.
5136TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5137 setFocusedWindow(mMirror);
5138
5139 // window gets focused
5140 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5142 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005143 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5145 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005146 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5147
5148 mMirror->setVisible(false);
5149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5150
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5152 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005153 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5155 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005156 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5157
5158 mWindow->setVisible(false);
5159 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5160
5161 // window loses focus only after all windows associated with the token become invisible.
5162 mWindow->consumeFocusEvent(false);
5163
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005164 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5165 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005166 mWindow->assertNoEvents();
5167}
5168
5169// A focused & mirrored window remains focused until both windows are removed.
5170TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5171 setFocusedWindow(mMirror);
5172
5173 // window gets focused
5174 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005175 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5176 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005177 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005178 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5179 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005180 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5181
5182 // single window is removed but the window token remains focused
5183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5184
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5186 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005187 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5189 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005190 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5191
5192 // Both windows are removed
5193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5194 mWindow->consumeFocusEvent(false);
5195
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005196 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5197 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005198 mWindow->assertNoEvents();
5199}
5200
5201// Focus request can be pending until one window becomes visible.
5202TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5203 // Request focus on an invisible mirror.
5204 mWindow->setVisible(false);
5205 mMirror->setVisible(false);
5206 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5207 setFocusedWindow(mMirror);
5208
5209 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005211 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005212 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005213
5214 mMirror->setVisible(true);
5215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5216
5217 // window gets focused
5218 mWindow->consumeFocusEvent(true);
5219 // window gets the pending key event
5220 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5221}
Prabir Pradhan99987712020-11-10 18:43:05 -08005222
5223class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5224protected:
5225 std::shared_ptr<FakeApplicationHandle> mApp;
5226 sp<FakeWindowHandle> mWindow;
5227 sp<FakeWindowHandle> mSecondWindow;
5228
5229 void SetUp() override {
5230 InputDispatcherTest::SetUp();
5231 mApp = std::make_shared<FakeApplicationHandle>();
5232 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5233 mWindow->setFocusable(true);
5234 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5235 mSecondWindow->setFocusable(true);
5236
5237 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5239
5240 setFocusedWindow(mWindow);
5241 mWindow->consumeFocusEvent(true);
5242 }
5243
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005244 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5245 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005246 mDispatcher->notifyPointerCaptureChanged(&args);
5247 }
5248
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005249 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5250 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005251 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005252 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5253 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005254 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005255 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005256 }
5257};
5258
5259TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5260 // Ensure that capture cannot be obtained for unfocused windows.
5261 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5262 mFakePolicy->assertSetPointerCaptureNotCalled();
5263 mSecondWindow->assertNoEvents();
5264
5265 // Ensure that capture can be enabled from the focus window.
5266 requestAndVerifyPointerCapture(mWindow, true);
5267
5268 // Ensure that capture cannot be disabled from a window that does not have capture.
5269 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5270 mFakePolicy->assertSetPointerCaptureNotCalled();
5271
5272 // Ensure that capture can be disabled from the window with capture.
5273 requestAndVerifyPointerCapture(mWindow, false);
5274}
5275
5276TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005277 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005278
5279 setFocusedWindow(mSecondWindow);
5280
5281 // Ensure that the capture disabled event was sent first.
5282 mWindow->consumeCaptureEvent(false);
5283 mWindow->consumeFocusEvent(false);
5284 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005285 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005286
5287 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005288 notifyPointerCaptureChanged({});
5289 notifyPointerCaptureChanged(request);
5290 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005291 mWindow->assertNoEvents();
5292 mSecondWindow->assertNoEvents();
5293 mFakePolicy->assertSetPointerCaptureNotCalled();
5294}
5295
5296TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005297 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005298
5299 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005300 notifyPointerCaptureChanged({});
5301 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005302
5303 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005304 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005305 mWindow->consumeCaptureEvent(false);
5306 mWindow->assertNoEvents();
5307}
5308
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005309TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5310 requestAndVerifyPointerCapture(mWindow, true);
5311
5312 // The first window loses focus.
5313 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005314 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005315 mWindow->consumeCaptureEvent(false);
5316
5317 // Request Pointer Capture from the second window before the notification from InputReader
5318 // arrives.
5319 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005320 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005321
5322 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005323 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005324
5325 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005326 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005327
5328 mSecondWindow->consumeFocusEvent(true);
5329 mSecondWindow->consumeCaptureEvent(true);
5330}
5331
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005332TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5333 // App repeatedly enables and disables capture.
5334 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5335 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5336 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5337 mFakePolicy->assertSetPointerCaptureCalled(false);
5338 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5339 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5340
5341 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5342 // first request is now stale, this should do nothing.
5343 notifyPointerCaptureChanged(firstRequest);
5344 mWindow->assertNoEvents();
5345
5346 // InputReader notifies that the second request was enabled.
5347 notifyPointerCaptureChanged(secondRequest);
5348 mWindow->consumeCaptureEvent(true);
5349}
5350
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005351class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5352protected:
5353 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005354
5355 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5356 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5357
5358 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5359 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5360
5361 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5362 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5363 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5364 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5365 MAXIMUM_OBSCURING_OPACITY);
5366
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005367 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005368 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005369 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005370
5371 sp<FakeWindowHandle> mTouchWindow;
5372
5373 virtual void SetUp() override {
5374 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005375 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005376 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5377 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5378 }
5379
5380 virtual void TearDown() override {
5381 InputDispatcherTest::TearDown();
5382 mTouchWindow.clear();
5383 }
5384
chaviw3277faf2021-05-19 16:45:23 -05005385 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5386 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005387 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005388 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005389 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005390 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005391 return window;
5392 }
5393
5394 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5395 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5396 sp<FakeWindowHandle> window =
5397 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5398 // Generate an arbitrary PID based on the UID
5399 window->setOwnerInfo(1777 + (uid % 10000), uid);
5400 return window;
5401 }
5402
5403 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5404 NotifyMotionArgs args =
5405 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5406 ADISPLAY_ID_DEFAULT, points);
5407 mDispatcher->notifyMotion(&args);
5408 }
5409};
5410
5411TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005412 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005413 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005415
5416 touch();
5417
5418 mTouchWindow->assertNoEvents();
5419}
5420
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005421TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005422 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5423 const sp<FakeWindowHandle>& w =
5424 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5426
5427 touch();
5428
5429 mTouchWindow->assertNoEvents();
5430}
5431
5432TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005433 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5434 const sp<FakeWindowHandle>& w =
5435 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5437
5438 touch();
5439
5440 w->assertNoEvents();
5441}
5442
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005443TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005444 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005446
5447 touch();
5448
5449 mTouchWindow->consumeAnyMotionDown();
5450}
5451
5452TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005453 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005454 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005455 w->setFrame(Rect(0, 0, 50, 50));
5456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005457
5458 touch({PointF{100, 100}});
5459
5460 mTouchWindow->consumeAnyMotionDown();
5461}
5462
5463TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005464 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005465 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5467
5468 touch();
5469
5470 mTouchWindow->consumeAnyMotionDown();
5471}
5472
5473TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5474 const sp<FakeWindowHandle>& w =
5475 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5476 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005477
5478 touch();
5479
5480 mTouchWindow->consumeAnyMotionDown();
5481}
5482
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005483TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5484 const sp<FakeWindowHandle>& w =
5485 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5486 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5487
5488 touch();
5489
5490 w->assertNoEvents();
5491}
5492
5493/**
5494 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5495 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5496 * window, the occluding window will still receive ACTION_OUTSIDE event.
5497 */
5498TEST_F(InputDispatcherUntrustedTouchesTest,
5499 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5500 const sp<FakeWindowHandle>& w =
5501 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005502 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5504
5505 touch();
5506
5507 w->consumeMotionOutside();
5508}
5509
5510TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5511 const sp<FakeWindowHandle>& w =
5512 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005513 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5515
5516 touch();
5517
5518 InputEvent* event = w->consume();
5519 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5520 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5521 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5522 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5523}
5524
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005525TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005526 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005527 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5528 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5530
5531 touch();
5532
5533 mTouchWindow->consumeAnyMotionDown();
5534}
5535
5536TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5537 const sp<FakeWindowHandle>& w =
5538 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5539 MAXIMUM_OBSCURING_OPACITY);
5540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005541
5542 touch();
5543
5544 mTouchWindow->consumeAnyMotionDown();
5545}
5546
5547TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005548 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005549 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5550 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5552
5553 touch();
5554
5555 mTouchWindow->assertNoEvents();
5556}
5557
5558TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5559 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5560 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005561 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5562 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005564 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5565 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5567
5568 touch();
5569
5570 mTouchWindow->assertNoEvents();
5571}
5572
5573TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5574 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5575 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005576 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5577 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005578 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005579 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5580 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5582
5583 touch();
5584
5585 mTouchWindow->consumeAnyMotionDown();
5586}
5587
5588TEST_F(InputDispatcherUntrustedTouchesTest,
5589 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5590 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 Rufino1d0d1f22021-02-12 15:08:43 +00005593 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005594 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5595 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5597
5598 touch();
5599
5600 mTouchWindow->consumeAnyMotionDown();
5601}
5602
5603TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5604 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005605 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5606 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005607 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005608 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5609 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005611
5612 touch();
5613
5614 mTouchWindow->assertNoEvents();
5615}
5616
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005617TEST_F(InputDispatcherUntrustedTouchesTest,
5618 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5619 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005620 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5621 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005622 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005623 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5624 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5626
5627 touch();
5628
5629 mTouchWindow->assertNoEvents();
5630}
5631
5632TEST_F(InputDispatcherUntrustedTouchesTest,
5633 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5634 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005635 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5636 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005637 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005638 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5639 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5641
5642 touch();
5643
5644 mTouchWindow->consumeAnyMotionDown();
5645}
5646
5647TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5648 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005649 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5650 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5652
5653 touch();
5654
5655 mTouchWindow->consumeAnyMotionDown();
5656}
5657
5658TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5659 const sp<FakeWindowHandle>& w =
5660 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5662
5663 touch();
5664
5665 mTouchWindow->consumeAnyMotionDown();
5666}
5667
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005668TEST_F(InputDispatcherUntrustedTouchesTest,
5669 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5670 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5671 const sp<FakeWindowHandle>& w =
5672 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5674
5675 touch();
5676
5677 mTouchWindow->assertNoEvents();
5678}
5679
5680TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5681 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5682 const sp<FakeWindowHandle>& w =
5683 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5685
5686 touch();
5687
5688 mTouchWindow->consumeAnyMotionDown();
5689}
5690
5691TEST_F(InputDispatcherUntrustedTouchesTest,
5692 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5693 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5694 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005695 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5696 OPACITY_ABOVE_THRESHOLD);
5697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5698
5699 touch();
5700
5701 mTouchWindow->consumeAnyMotionDown();
5702}
5703
5704TEST_F(InputDispatcherUntrustedTouchesTest,
5705 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5706 const sp<FakeWindowHandle>& w1 =
5707 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5708 OPACITY_BELOW_THRESHOLD);
5709 const sp<FakeWindowHandle>& w2 =
5710 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5711 OPACITY_BELOW_THRESHOLD);
5712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5713
5714 touch();
5715
5716 mTouchWindow->assertNoEvents();
5717}
5718
5719/**
5720 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5721 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5722 * (which alone would result in allowing touches) does not affect the blocking behavior.
5723 */
5724TEST_F(InputDispatcherUntrustedTouchesTest,
5725 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5726 const sp<FakeWindowHandle>& wB =
5727 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5728 OPACITY_BELOW_THRESHOLD);
5729 const sp<FakeWindowHandle>& wC =
5730 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5731 OPACITY_BELOW_THRESHOLD);
5732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5733
5734 touch();
5735
5736 mTouchWindow->assertNoEvents();
5737}
5738
5739/**
5740 * This test is testing that a window from a different UID but with same application token doesn't
5741 * block the touch. Apps can share the application token for close UI collaboration for example.
5742 */
5743TEST_F(InputDispatcherUntrustedTouchesTest,
5744 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5745 const sp<FakeWindowHandle>& w =
5746 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5747 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5749
5750 touch();
5751
5752 mTouchWindow->consumeAnyMotionDown();
5753}
5754
arthurhungb89ccb02020-12-30 16:19:01 +08005755class InputDispatcherDragTests : public InputDispatcherTest {
5756protected:
5757 std::shared_ptr<FakeApplicationHandle> mApp;
5758 sp<FakeWindowHandle> mWindow;
5759 sp<FakeWindowHandle> mSecondWindow;
5760 sp<FakeWindowHandle> mDragWindow;
5761
5762 void SetUp() override {
5763 InputDispatcherTest::SetUp();
5764 mApp = std::make_shared<FakeApplicationHandle>();
5765 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5766 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005767 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005768
5769 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5770 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005771 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005772
5773 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5775 }
5776
5777 // Start performing drag, we will create a drag window and transfer touch to it.
5778 void performDrag() {
5779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5781 {50, 50}))
5782 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5783
5784 // Window should receive motion event.
5785 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5786
5787 // The drag window covers the entire display
5788 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5789 mDispatcher->setInputWindows(
5790 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5791
5792 // Transfer touch focus to the drag window
5793 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5794 true /* isDragDrop */);
5795 mWindow->consumeMotionCancel();
5796 mDragWindow->consumeMotionDown();
5797 }
arthurhung6d4bed92021-03-17 11:59:33 +08005798
5799 // Start performing drag, we will create a drag window and transfer touch to it.
5800 void performStylusDrag() {
5801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5802 injectMotionEvent(mDispatcher,
5803 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5804 AINPUT_SOURCE_STYLUS)
5805 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5806 .pointer(PointerBuilder(0,
5807 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5808 .x(50)
5809 .y(50))
5810 .build()));
5811 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5812
5813 // The drag window covers the entire display
5814 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5815 mDispatcher->setInputWindows(
5816 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5817
5818 // Transfer touch focus to the drag window
5819 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5820 true /* isDragDrop */);
5821 mWindow->consumeMotionCancel();
5822 mDragWindow->consumeMotionDown();
5823 }
arthurhungb89ccb02020-12-30 16:19:01 +08005824};
5825
5826TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5827 performDrag();
5828
5829 // Move on window.
5830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5831 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5832 ADISPLAY_ID_DEFAULT, {50, 50}))
5833 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5834 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5835 mWindow->consumeDragEvent(false, 50, 50);
5836 mSecondWindow->assertNoEvents();
5837
5838 // Move to another window.
5839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5840 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5841 ADISPLAY_ID_DEFAULT, {150, 50}))
5842 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5843 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5844 mWindow->consumeDragEvent(true, 150, 50);
5845 mSecondWindow->consumeDragEvent(false, 50, 50);
5846
5847 // Move back to original window.
5848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5849 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5850 ADISPLAY_ID_DEFAULT, {50, 50}))
5851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5852 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5853 mWindow->consumeDragEvent(false, 50, 50);
5854 mSecondWindow->consumeDragEvent(true, -50, 50);
5855
5856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5857 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5858 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5859 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5860 mWindow->assertNoEvents();
5861 mSecondWindow->assertNoEvents();
5862}
5863
arthurhungf452d0b2021-01-06 00:19:52 +08005864TEST_F(InputDispatcherDragTests, DragAndDrop) {
5865 performDrag();
5866
5867 // Move on window.
5868 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5869 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5870 ADISPLAY_ID_DEFAULT, {50, 50}))
5871 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5872 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5873 mWindow->consumeDragEvent(false, 50, 50);
5874 mSecondWindow->assertNoEvents();
5875
5876 // Move to another window.
5877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5878 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5879 ADISPLAY_ID_DEFAULT, {150, 50}))
5880 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5881 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5882 mWindow->consumeDragEvent(true, 150, 50);
5883 mSecondWindow->consumeDragEvent(false, 50, 50);
5884
5885 // drop to another window.
5886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5887 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5888 {150, 50}))
5889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5890 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5891 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5892 mWindow->assertNoEvents();
5893 mSecondWindow->assertNoEvents();
5894}
5895
arthurhung6d4bed92021-03-17 11:59:33 +08005896TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5897 performStylusDrag();
5898
5899 // Move on window and keep button pressed.
5900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5901 injectMotionEvent(mDispatcher,
5902 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5903 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5904 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5905 .x(50)
5906 .y(50))
5907 .build()))
5908 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5909 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5910 mWindow->consumeDragEvent(false, 50, 50);
5911 mSecondWindow->assertNoEvents();
5912
5913 // Move to another window and release button, expect to drop item.
5914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5915 injectMotionEvent(mDispatcher,
5916 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5917 .buttonState(0)
5918 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5919 .x(150)
5920 .y(50))
5921 .build()))
5922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5923 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5924 mWindow->assertNoEvents();
5925 mSecondWindow->assertNoEvents();
5926 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5927
5928 // nothing to the window.
5929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5930 injectMotionEvent(mDispatcher,
5931 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5932 .buttonState(0)
5933 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5934 .x(150)
5935 .y(50))
5936 .build()))
5937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5938 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5939 mWindow->assertNoEvents();
5940 mSecondWindow->assertNoEvents();
5941}
5942
Arthur Hung6d0571e2021-04-09 20:18:16 +08005943TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5944 performDrag();
5945
5946 // Set second window invisible.
5947 mSecondWindow->setVisible(false);
5948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5949
5950 // Move on window.
5951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5952 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5953 ADISPLAY_ID_DEFAULT, {50, 50}))
5954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5955 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5956 mWindow->consumeDragEvent(false, 50, 50);
5957 mSecondWindow->assertNoEvents();
5958
5959 // Move to another window.
5960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5961 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5962 ADISPLAY_ID_DEFAULT, {150, 50}))
5963 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5964 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5965 mWindow->consumeDragEvent(true, 150, 50);
5966 mSecondWindow->assertNoEvents();
5967
5968 // drop to another window.
5969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5970 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5971 {150, 50}))
5972 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5973 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5974 mFakePolicy->assertDropTargetEquals(nullptr);
5975 mWindow->assertNoEvents();
5976 mSecondWindow->assertNoEvents();
5977}
5978
Vishnu Nair062a8672021-09-03 16:07:44 -07005979class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
5980
5981TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
5982 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
5983 sp<FakeWindowHandle> window =
5984 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
5985 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
5986 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
5987 window->setFocusable(true);
5988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
5989 setFocusedWindow(window);
5990 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
5991
5992 // With the flag set, window should not get any input
5993 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
5994 mDispatcher->notifyKey(&keyArgs);
5995 window->assertNoEvents();
5996
5997 NotifyMotionArgs motionArgs =
5998 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5999 ADISPLAY_ID_DEFAULT);
6000 mDispatcher->notifyMotion(&motionArgs);
6001 window->assertNoEvents();
6002
6003 // With the flag cleared, the window should get input
6004 window->setInputFeatures({});
6005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6006
6007 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6008 mDispatcher->notifyKey(&keyArgs);
6009 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6010
6011 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6012 ADISPLAY_ID_DEFAULT);
6013 mDispatcher->notifyMotion(&motionArgs);
6014 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6015 window->assertNoEvents();
6016}
6017
6018TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6019 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6020 std::make_shared<FakeApplicationHandle>();
6021 sp<FakeWindowHandle> obscuringWindow =
6022 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6023 ADISPLAY_ID_DEFAULT);
6024 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6025 obscuringWindow->setOwnerInfo(111, 111);
6026 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6027 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6028 sp<FakeWindowHandle> window =
6029 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6030 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6031 window->setOwnerInfo(222, 222);
6032 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6033 window->setFocusable(true);
6034 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6035 setFocusedWindow(window);
6036 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6037
6038 // With the flag set, window should not get any input
6039 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6040 mDispatcher->notifyKey(&keyArgs);
6041 window->assertNoEvents();
6042
6043 NotifyMotionArgs motionArgs =
6044 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6045 ADISPLAY_ID_DEFAULT);
6046 mDispatcher->notifyMotion(&motionArgs);
6047 window->assertNoEvents();
6048
6049 // With the flag cleared, the window should get input
6050 window->setInputFeatures({});
6051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6052
6053 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6054 mDispatcher->notifyKey(&keyArgs);
6055 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6056
6057 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6058 ADISPLAY_ID_DEFAULT);
6059 mDispatcher->notifyMotion(&motionArgs);
6060 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6061 window->assertNoEvents();
6062}
6063
6064TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6065 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6066 std::make_shared<FakeApplicationHandle>();
6067 sp<FakeWindowHandle> obscuringWindow =
6068 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6069 ADISPLAY_ID_DEFAULT);
6070 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6071 obscuringWindow->setOwnerInfo(111, 111);
6072 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6073 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6074 sp<FakeWindowHandle> window =
6075 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6076 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6077 window->setOwnerInfo(222, 222);
6078 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6079 window->setFocusable(true);
6080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6081 setFocusedWindow(window);
6082 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6083
6084 // With the flag set, window should not get any input
6085 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6086 mDispatcher->notifyKey(&keyArgs);
6087 window->assertNoEvents();
6088
6089 NotifyMotionArgs motionArgs =
6090 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6091 ADISPLAY_ID_DEFAULT);
6092 mDispatcher->notifyMotion(&motionArgs);
6093 window->assertNoEvents();
6094
6095 // When the window is no longer obscured because it went on top, it should get input
6096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6097
6098 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6099 mDispatcher->notifyKey(&keyArgs);
6100 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6101
6102 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6103 ADISPLAY_ID_DEFAULT);
6104 mDispatcher->notifyMotion(&motionArgs);
6105 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6106 window->assertNoEvents();
6107}
6108
Antonio Kantekf16f2832021-09-28 04:39:20 +00006109class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6110protected:
6111 std::shared_ptr<FakeApplicationHandle> mApp;
6112 sp<FakeWindowHandle> mWindow;
6113 sp<FakeWindowHandle> mSecondWindow;
6114
6115 void SetUp() override {
6116 InputDispatcherTest::SetUp();
6117
6118 mApp = std::make_shared<FakeApplicationHandle>();
6119 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6120 mWindow->setFocusable(true);
6121 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6122 mSecondWindow->setFocusable(true);
6123
6124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6126
6127 setFocusedWindow(mWindow);
6128 mWindow->consumeFocusEvent(true);
6129 }
6130
6131 void changeAndVerifyTouchMode(bool inTouchMode) {
6132 mDispatcher->setInTouchMode(inTouchMode);
6133 mWindow->consumeTouchModeEvent(inTouchMode);
6134 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6135 }
6136};
6137
6138TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6139 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6140}
6141
6142TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6143 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6144 mWindow->assertNoEvents();
6145 mSecondWindow->assertNoEvents();
6146}
6147
Garfield Tane84e6f92019-08-29 17:28:41 -07006148} // namespace android::inputdispatcher