blob: f028349daaecdf7f77862d63be840a7d2e8d6c4e [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
Garfield Tan1c7bc862020-01-28 13:24:04 -080019#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070020#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070021#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080022#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100023#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025
Garfield Tan1c7bc862020-01-28 13:24:04 -080026#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070027#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080029#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080030
Garfield Tan1c7bc862020-01-28 13:24:04 -080031using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050032using android::gui::FocusRequest;
33using android::gui::TouchOcclusionMode;
34using android::gui::WindowInfo;
35using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080036using android::os::InputEventInjectionResult;
37using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010038using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080039
Garfield Tane84e6f92019-08-29 17:28:41 -070040namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080041
42// An arbitrary time value.
43static const nsecs_t ARBITRARY_TIME = 1234;
44
45// An arbitrary device id.
46static const int32_t DEVICE_ID = 1;
47
Jeff Brownf086ddb2014-02-11 14:28:48 -080048// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000049static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
50static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080051
Michael Wrightd02c5b62014-02-10 15:10:22 -080052// An arbitrary injector pid / uid pair that has permission to inject events.
53static const int32_t INJECTOR_PID = 999;
54static const int32_t INJECTOR_UID = 1001;
55
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000056// An arbitrary pid of the gesture monitor window
57static constexpr int32_t MONITOR_PID = 2001;
58
chaviwd1c23182019-12-20 18:44:56 -080059struct PointF {
60 float x;
61 float y;
62};
Michael Wrightd02c5b62014-02-10 15:10:22 -080063
Gang Wang342c9272020-01-13 13:15:04 -050064/**
65 * Return a DOWN key event with KEYCODE_A.
66 */
67static KeyEvent getTestKeyEvent() {
68 KeyEvent event;
69
Garfield Tanfbe732e2020-01-24 11:26:14 -080070 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
71 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
72 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050073 return event;
74}
75
Michael Wrightd02c5b62014-02-10 15:10:22 -080076// --- FakeInputDispatcherPolicy ---
77
78class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
79 InputDispatcherConfiguration mConfig;
80
81protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100082 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080083
84public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100085 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080086
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080087 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080088 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
89 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080090 }
91
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080092 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080093 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
94 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080095 }
96
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070097 void assertFilterInputEventWasNotCalled() {
98 std::scoped_lock lock(mLock);
99 ASSERT_EQ(nullptr, mFilteredEvent);
100 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800102 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700103 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800104 ASSERT_TRUE(mConfigurationChangedTime)
105 << "Timed out waiting for configuration changed call";
106 ASSERT_EQ(*mConfigurationChangedTime, when);
107 mConfigurationChangedTime = std::nullopt;
108 }
109
110 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700111 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800112 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800113 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800114 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
115 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
116 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
117 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
118 mLastNotifySwitch = std::nullopt;
119 }
120
chaviwfd6d3512019-03-25 13:23:49 -0700121 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700122 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800123 ASSERT_EQ(touchedToken, mOnPointerDownToken);
124 mOnPointerDownToken.clear();
125 }
126
127 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700128 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800129 ASSERT_TRUE(mOnPointerDownToken == nullptr)
130 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700131 }
132
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700133 // This function must be called soon after the expected ANR timer starts,
134 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500135 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700136 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500137 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
138 std::shared_ptr<InputApplicationHandle> application;
139 { // acquire lock
140 std::unique_lock lock(mLock);
141 android::base::ScopedLockAssertion assumeLocked(mLock);
142 ASSERT_NO_FATAL_FAILURE(
143 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
144 } // release lock
145 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700146 }
147
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000148 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
149 const sp<IBinder>& expectedConnectionToken) {
150 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500151 ASSERT_EQ(expectedConnectionToken, connectionToken);
152 }
153
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000154 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
155 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500156 ASSERT_EQ(expectedConnectionToken, connectionToken);
157 }
158
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000159 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
160 int32_t pid = getUnresponsiveMonitorPid(timeout);
161 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500162 }
163
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000164 void assertNotifyMonitorResponsiveWasCalled() {
165 int32_t pid = getResponsiveMonitorPid();
166 ASSERT_EQ(MONITOR_PID, pid);
167 }
168
169 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500170 std::unique_lock lock(mLock);
171 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000172 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
173 }
174
175 sp<IBinder> getResponsiveWindowToken() {
176 std::unique_lock lock(mLock);
177 android::base::ScopedLockAssertion assumeLocked(mLock);
178 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
179 }
180
181 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
182 std::unique_lock lock(mLock);
183 android::base::ScopedLockAssertion assumeLocked(mLock);
184 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
185 }
186
187 int32_t getResponsiveMonitorPid() {
188 std::unique_lock lock(mLock);
189 android::base::ScopedLockAssertion assumeLocked(mLock);
190 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500191 }
192
193 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
194 // for a specific container to become non-empty. When the container is non-empty, return the
195 // first entry from the container and erase it.
196 template <class T>
197 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
198 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
199 const std::chrono::time_point start = std::chrono::steady_clock::now();
200 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700201
202 // If there is an ANR, Dispatcher won't be idle because there are still events
203 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
204 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500205 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
206 // to provide it some time to act. 100ms seems reasonable.
207 mNotifyAnr.wait_for(lock, timeToWait,
208 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700209 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500210 if (storage.empty()) {
211 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000212 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700213 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700214 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
215 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700216 if (std::chrono::abs(timeout - waited) > 100ms) {
217 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
218 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
219 << "ms, but waited "
220 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
221 << "ms instead";
222 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500223 T token = storage.front();
224 storage.pop();
225 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700226 }
227
228 void assertNotifyAnrWasNotCalled() {
229 std::scoped_lock lock(mLock);
230 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000231 ASSERT_TRUE(mAnrWindowTokens.empty());
232 ASSERT_TRUE(mAnrMonitorPids.empty());
233 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500234 << "ANR was not called, but please also consume the 'connection is responsive' "
235 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000236 ASSERT_TRUE(mResponsiveMonitorPids.empty())
237 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
238 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700239 }
240
Garfield Tan1c7bc862020-01-28 13:24:04 -0800241 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
242 mConfig.keyRepeatTimeout = timeout;
243 mConfig.keyRepeatDelay = delay;
244 }
245
Prabir Pradhanac483a62021-08-06 14:01:18 +0000246 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800247 std::unique_lock lock(mLock);
248 base::ScopedLockAssertion assumeLocked(mLock);
249
250 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
251 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhanac483a62021-08-06 14:01:18 +0000252 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800253 enabled;
254 })) {
Prabir Pradhanac483a62021-08-06 14:01:18 +0000255 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
256 << ") to be called.";
257 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800258 }
Prabir Pradhanac483a62021-08-06 14:01:18 +0000259 auto request = *mPointerCaptureRequest;
260 mPointerCaptureRequest.reset();
261 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800262 }
263
264 void assertSetPointerCaptureNotCalled() {
265 std::unique_lock lock(mLock);
266 base::ScopedLockAssertion assumeLocked(mLock);
267
268 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhanac483a62021-08-06 14:01:18 +0000269 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800270 "enabled = "
Prabir Pradhanac483a62021-08-06 14:01:18 +0000271 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800272 }
Prabir Pradhanac483a62021-08-06 14:01:18 +0000273 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800274 }
275
arthurhungf452d0b2021-01-06 00:19:52 +0800276 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
277 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800278 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800279 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800280 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800281 }
282
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700284 std::mutex mLock;
285 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
286 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
287 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
288 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800289
Prabir Pradhan99987712020-11-10 18:43:05 -0800290 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhanac483a62021-08-06 14:01:18 +0000291
292 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800293
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700294 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700295 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000296 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
297 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
298 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
299 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700300 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700301
arthurhungf452d0b2021-01-06 00:19:52 +0800302 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800303 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800304
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600305 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700306 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800307 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800308 }
309
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000310 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700311 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000312 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700313 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500314 }
315
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000316 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500317 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000318 mAnrMonitorPids.push(pid);
319 mNotifyAnr.notify_all();
320 }
321
322 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
323 std::scoped_lock lock(mLock);
324 mResponsiveWindowTokens.push(connectionToken);
325 mNotifyAnr.notify_all();
326 }
327
328 void notifyMonitorResponsive(int32_t pid) override {
329 std::scoped_lock lock(mLock);
330 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500331 mNotifyAnr.notify_all();
332 }
333
334 void notifyNoFocusedWindowAnr(
335 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
336 std::scoped_lock lock(mLock);
337 mAnrApplications.push(applicationHandle);
338 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800339 }
340
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600341 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800342
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600343 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700344
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600345 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700346 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
347 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
348 const std::vector<float>& values) override {}
349
350 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
351 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000352
Chris Yefb552902021-02-03 17:18:37 -0800353 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
354
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600355 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 *outConfig = mConfig;
357 }
358
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600359 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700360 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800361 switch (inputEvent->getType()) {
362 case AINPUT_EVENT_TYPE_KEY: {
363 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800364 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800365 break;
366 }
367
368 case AINPUT_EVENT_TYPE_MOTION: {
369 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800370 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800371 break;
372 }
373 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374 return true;
375 }
376
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600377 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600379 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800382 return 0;
383 }
384
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600385 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800386 return false;
387 }
388
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600389 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
390 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700391 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800392 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
393 * essentially a passthrough for notifySwitch.
394 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800395 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396 }
397
Sean Stoutb4e0a592021-02-23 07:34:53 -0800398 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800400 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
401 return pid == INJECTOR_PID && uid == INJECTOR_UID;
402 }
Jackal Guof9696682018-10-05 12:23:23 +0800403
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600404 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700405 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700406 mOnPointerDownToken = newToken;
407 }
408
Prabir Pradhanac483a62021-08-06 14:01:18 +0000409 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800410 std::scoped_lock lock(mLock);
Prabir Pradhanac483a62021-08-06 14:01:18 +0000411 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800412 mPointerCaptureChangedCondition.notify_all();
413 }
414
arthurhungf452d0b2021-01-06 00:19:52 +0800415 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
416 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800417 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800418 mDropTargetWindowToken = token;
419 }
420
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800421 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
422 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700423 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800424 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
425 ASSERT_EQ(mFilteredEvent->getType(), type);
426
427 if (type == AINPUT_EVENT_TYPE_KEY) {
428 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
429 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
430 EXPECT_EQ(keyEvent.getAction(), action);
431 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
432 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
433 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
434 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
435 EXPECT_EQ(motionEvent.getAction(), action);
436 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
437 } else {
438 FAIL() << "Unknown type: " << type;
439 }
440
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800441 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443};
444
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445// --- InputDispatcherTest ---
446
447class InputDispatcherTest : public testing::Test {
448protected:
449 sp<FakeInputDispatcherPolicy> mFakePolicy;
450 sp<InputDispatcher> mDispatcher;
451
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000452 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 mFakePolicy = new FakeInputDispatcherPolicy();
454 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800455 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000456 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700457 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 }
459
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000460 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700461 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 mFakePolicy.clear();
463 mDispatcher.clear();
464 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700465
466 /**
467 * Used for debugging when writing the test
468 */
469 void dumpDispatcherState() {
470 std::string dump;
471 mDispatcher->dump(dump);
472 std::stringstream ss(dump);
473 std::string to;
474
475 while (std::getline(ss, to, '\n')) {
476 ALOGE("%s", to.c_str());
477 }
478 }
Vishnu Nair958da932020-08-21 17:12:37 -0700479
chaviw3277faf2021-05-19 16:45:23 -0500480 void setFocusedWindow(const sp<WindowInfoHandle>& window,
481 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700482 FocusRequest request;
483 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000484 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700485 if (focusedWindow) {
486 request.focusedToken = focusedWindow->getToken();
487 }
488 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
489 request.displayId = window->getInfo()->displayId;
490 mDispatcher->setFocusedWindow(request);
491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492};
493
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
495 KeyEvent event;
496
497 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800498 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
499 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600500 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
501 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800502 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700503 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800504 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 << "Should reject key events with undefined action.";
506
507 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800508 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
509 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600510 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800511 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700512 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800513 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 << "Should reject key events with ACTION_MULTIPLE.";
515}
516
517TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
518 MotionEvent event;
519 PointerProperties pointerProperties[MAX_POINTERS + 1];
520 PointerCoords pointerCoords[MAX_POINTERS + 1];
521 for (int i = 0; i <= MAX_POINTERS; i++) {
522 pointerProperties[i].clear();
523 pointerProperties[i].id = i;
524 pointerCoords[i].clear();
525 }
526
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800527 // Some constants commonly used below
528 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
529 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
530 constexpr int32_t metaState = AMETA_NONE;
531 constexpr MotionClassification classification = MotionClassification::NONE;
532
chaviw9eaa22c2020-07-01 16:21:27 -0700533 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800535 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700536 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
537 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700538 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
539 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700540 /*pointerCount*/ 1, pointerProperties, pointerCoords);
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 motion events with undefined action.";
545
546 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800547 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700548 AMOTION_EVENT_ACTION_POINTER_DOWN |
549 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700550 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
551 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700552 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
553 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500554 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800555 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700556 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800557 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558 << "Should reject motion events with pointer down index too large.";
559
Garfield Tanfbe732e2020-01-24 11:26:14 -0800560 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700561 AMOTION_EVENT_ACTION_POINTER_DOWN |
562 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700563 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
564 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700565 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
566 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500567 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800568 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700569 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800570 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571 << "Should reject motion events with pointer down index too small.";
572
573 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800574 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700575 AMOTION_EVENT_ACTION_POINTER_UP |
576 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700577 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
578 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700579 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
580 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500581 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800582 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700583 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800584 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 << "Should reject motion events with pointer up index too large.";
586
Garfield Tanfbe732e2020-01-24 11:26:14 -0800587 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700588 AMOTION_EVENT_ACTION_POINTER_UP |
589 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700590 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
591 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700592 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
593 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500594 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700596 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800597 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 << "Should reject motion events with pointer up index too small.";
599
600 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800601 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
602 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700603 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700604 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
605 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700606 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700608 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 << "Should reject motion events with 0 pointers.";
611
Garfield Tanfbe732e2020-01-24 11:26:14 -0800612 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
613 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700614 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700615 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
616 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700617 /*pointerCount*/ MAX_POINTERS + 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 more than MAX_POINTERS pointers.";
622
623 // Rejects motion events with invalid pointer ids.
624 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800625 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
626 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700627 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700628 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
629 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700630 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800631 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700632 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800633 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 << "Should reject motion events with pointer ids less than 0.";
635
636 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800637 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
638 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700639 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700640 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
641 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700642 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800643 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700644 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800645 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
647
648 // Rejects motion events with duplicate pointer ids.
649 pointerProperties[0].id = 1;
650 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800651 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
652 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700653 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700654 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
655 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700656 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800657 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700658 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800659 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 << "Should reject motion events with duplicate pointer ids.";
661}
662
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800663/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
664
665TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
666 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800667 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800668 mDispatcher->notifyConfigurationChanged(&args);
669 ASSERT_TRUE(mDispatcher->waitForIdle());
670
671 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
672}
673
674TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800675 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
676 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800677 mDispatcher->notifySwitch(&args);
678
679 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
680 args.policyFlags |= POLICY_FLAG_TRUSTED;
681 mFakePolicy->assertNotifySwitchWasCalled(args);
682}
683
Arthur Hungb92218b2018-08-14 12:00:21 +0800684// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700685static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700686static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800687
688class FakeApplicationHandle : public InputApplicationHandle {
689public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700690 FakeApplicationHandle() {
691 mInfo.name = "Fake Application";
692 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500693 mInfo.dispatchingTimeoutMillis =
694 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700695 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800696 virtual ~FakeApplicationHandle() {}
697
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000698 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700699
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500700 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
701 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700702 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800703};
704
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800705class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800706public:
Garfield Tan15601662020-09-22 15:32:38 -0700707 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800708 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700709 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800710 }
711
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800712 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700713 InputEvent* event;
714 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
715 if (!consumeSeq) {
716 return nullptr;
717 }
718 finishEvent(*consumeSeq);
719 return event;
720 }
721
722 /**
723 * Receive an event without acknowledging it.
724 * Return the sequence number that could later be used to send finished signal.
725 */
726 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800727 uint32_t consumeSeq;
728 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800729
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800730 std::chrono::time_point start = std::chrono::steady_clock::now();
731 status_t status = WOULD_BLOCK;
732 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800733 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800734 &event);
735 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
736 if (elapsed > 100ms) {
737 break;
738 }
739 }
740
741 if (status == WOULD_BLOCK) {
742 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700743 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800744 }
745
746 if (status != OK) {
747 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700748 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800749 }
750 if (event == nullptr) {
751 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800753 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700754 if (outEvent != nullptr) {
755 *outEvent = event;
756 }
757 return consumeSeq;
758 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800759
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700760 /**
761 * To be used together with "receiveEvent" to complete the consumption of an event.
762 */
763 void finishEvent(uint32_t consumeSeq) {
764 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
765 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800766 }
767
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000768 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
769 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
770 ASSERT_EQ(OK, status);
771 }
772
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000773 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
774 std::optional<int32_t> expectedDisplayId,
775 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800776 InputEvent* event = consume();
777
778 ASSERT_NE(nullptr, event) << mName.c_str()
779 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800780 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700781 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800782 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800783
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000784 if (expectedDisplayId.has_value()) {
785 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
786 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800787
Tiger Huang8664f8c2018-10-11 19:14:35 +0800788 switch (expectedEventType) {
789 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800790 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
791 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000792 if (expectedFlags.has_value()) {
793 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
794 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800795 break;
796 }
797 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800798 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
799 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000800 if (expectedFlags.has_value()) {
801 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
802 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800803 break;
804 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100805 case AINPUT_EVENT_TYPE_FOCUS: {
806 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
807 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800808 case AINPUT_EVENT_TYPE_CAPTURE: {
809 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
810 }
arthurhungb89ccb02020-12-30 16:19:01 +0800811 case AINPUT_EVENT_TYPE_DRAG: {
812 FAIL() << "Use 'consumeDragEvent' for DRAG events";
813 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800814 default: {
815 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
816 }
817 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800818 }
819
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100820 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
821 InputEvent* event = consume();
822 ASSERT_NE(nullptr, event) << mName.c_str()
823 << ": consumer should have returned non-NULL event.";
824 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
825 << "Got " << inputEventTypeToString(event->getType())
826 << " event instead of FOCUS event";
827
828 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
829 << mName.c_str() << ": event displayId should always be NONE.";
830
831 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
832 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
833 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
834 }
835
Prabir Pradhan99987712020-11-10 18:43:05 -0800836 void consumeCaptureEvent(bool hasCapture) {
837 const InputEvent* event = consume();
838 ASSERT_NE(nullptr, event) << mName.c_str()
839 << ": consumer should have returned non-NULL event.";
840 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
841 << "Got " << inputEventTypeToString(event->getType())
842 << " event instead of CAPTURE event";
843
844 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
845 << mName.c_str() << ": event displayId should always be NONE.";
846
847 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
848 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
849 }
850
arthurhungb89ccb02020-12-30 16:19:01 +0800851 void consumeDragEvent(bool isExiting, float x, float y) {
852 const InputEvent* event = consume();
853 ASSERT_NE(nullptr, event) << mName.c_str()
854 << ": consumer should have returned non-NULL event.";
855 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
856 << "Got " << inputEventTypeToString(event->getType())
857 << " event instead of DRAG event";
858
859 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
860 << mName.c_str() << ": event displayId should always be NONE.";
861
862 const auto& dragEvent = static_cast<const DragEvent&>(*event);
863 EXPECT_EQ(isExiting, dragEvent.isExiting());
864 EXPECT_EQ(x, dragEvent.getX());
865 EXPECT_EQ(y, dragEvent.getY());
866 }
867
chaviwd1c23182019-12-20 18:44:56 -0800868 void assertNoEvents() {
869 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700870 if (event == nullptr) {
871 return;
872 }
873 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
874 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
875 ADD_FAILURE() << "Received key event "
876 << KeyEvent::actionToString(keyEvent.getAction());
877 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
878 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
879 ADD_FAILURE() << "Received motion event "
880 << MotionEvent::actionToString(motionEvent.getAction());
881 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
882 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
883 ADD_FAILURE() << "Received focus event, hasFocus = "
884 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800885 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
886 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
887 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
888 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700889 }
890 FAIL() << mName.c_str()
891 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800892 }
893
894 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
895
896protected:
897 std::unique_ptr<InputConsumer> mConsumer;
898 PreallocatedInputEventFactory mEventFactory;
899
900 std::string mName;
901};
902
chaviw3277faf2021-05-19 16:45:23 -0500903class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800904public:
905 static const int32_t WIDTH = 600;
906 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800907
Chris Yea209fde2020-07-22 13:54:51 -0700908 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800909 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500910 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800911 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500912 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700913 base::Result<std::unique_ptr<InputChannel>> channel =
914 dispatcher->createInputChannel(name);
915 token = (*channel)->getConnectionToken();
916 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800917 }
918
919 inputApplicationHandle->updateInfo();
920 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
921
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500922 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700923 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800924 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500925 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500926 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000927 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800928 mInfo.frameLeft = 0;
929 mInfo.frameTop = 0;
930 mInfo.frameRight = WIDTH;
931 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700932 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800933 mInfo.globalScaleFactor = 1.0;
934 mInfo.touchableRegion.clear();
935 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
936 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700937 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800938 mInfo.hasWallpaper = false;
939 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800940 mInfo.ownerPid = INJECTOR_PID;
941 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800942 mInfo.displayId = displayId;
943 }
944
Arthur Hungabbb9d82021-09-01 14:52:30 +0000945 sp<FakeWindowHandle> clone(
946 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
947 const sp<InputDispatcher>& dispatcher, int32_t displayId) {
948 sp<FakeWindowHandle> handle =
949 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
950 displayId, mInfo.token);
951 return handle;
952 }
953
Vishnu Nair47074b82020-08-14 11:54:47 -0700954 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800955
Vishnu Nair958da932020-08-21 17:12:37 -0700956 void setVisible(bool visible) { mInfo.visible = visible; }
957
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700958 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500959 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700960 }
961
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700962 void setPaused(bool paused) { mInfo.paused = paused; }
963
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000964 void setAlpha(float alpha) { mInfo.alpha = alpha; }
965
chaviw3277faf2021-05-19 16:45:23 -0500966 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000967
Bernardo Rufino7393d172021-02-26 13:56:11 +0000968 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
969
chaviwd1c23182019-12-20 18:44:56 -0800970 void setFrame(const Rect& frame) {
971 mInfo.frameLeft = frame.left;
972 mInfo.frameTop = frame.top;
973 mInfo.frameRight = frame.right;
974 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800975 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800976 mInfo.touchableRegion.clear();
977 mInfo.addTouchableRegion(frame);
978 }
979
chaviw3277faf2021-05-19 16:45:23 -0500980 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000981
chaviw3277faf2021-05-19 16:45:23 -0500982 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800983
chaviw3277faf2021-05-19 16:45:23 -0500984 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500985
chaviw9eaa22c2020-07-01 16:21:27 -0700986 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
987 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
988 }
989
990 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700991
yunho.shinf4a80b82020-11-16 21:13:57 +0900992 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
993
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800994 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
995 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
996 expectedFlags);
997 }
998
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700999 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1000 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1001 }
1002
Svet Ganov5d3bc372020-01-26 23:11:07 -08001003 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001004 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001005 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1006 expectedFlags);
1007 }
1008
1009 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001010 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001011 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1012 expectedFlags);
1013 }
1014
1015 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001016 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001017 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1018 }
1019
1020 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1021 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001022 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1023 expectedFlags);
1024 }
1025
Svet Ganov5d3bc372020-01-26 23:11:07 -08001026 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001027 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1028 int32_t expectedFlags = 0) {
1029 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1030 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001031 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1032 }
1033
1034 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001035 int32_t expectedFlags = 0) {
1036 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1037 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001038 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1039 }
1040
1041 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001042 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001043 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1044 expectedFlags);
1045 }
1046
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001047 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1048 int32_t expectedFlags = 0) {
1049 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1050 expectedFlags);
1051 }
1052
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001053 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1054 ASSERT_NE(mInputReceiver, nullptr)
1055 << "Cannot consume events from a window with no receiver";
1056 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1057 }
1058
Prabir Pradhan99987712020-11-10 18:43:05 -08001059 void consumeCaptureEvent(bool hasCapture) {
1060 ASSERT_NE(mInputReceiver, nullptr)
1061 << "Cannot consume events from a window with no receiver";
1062 mInputReceiver->consumeCaptureEvent(hasCapture);
1063 }
1064
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001065 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1066 std::optional<int32_t> expectedDisplayId,
1067 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001068 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1069 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1070 expectedFlags);
1071 }
1072
arthurhungb89ccb02020-12-30 16:19:01 +08001073 void consumeDragEvent(bool isExiting, float x, float y) {
1074 mInputReceiver->consumeDragEvent(isExiting, x, y);
1075 }
1076
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001077 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001078 if (mInputReceiver == nullptr) {
1079 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1080 return std::nullopt;
1081 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001082 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001083 }
1084
1085 void finishEvent(uint32_t sequenceNum) {
1086 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1087 mInputReceiver->finishEvent(sequenceNum);
1088 }
1089
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001090 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1091 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1092 mInputReceiver->sendTimeline(inputEventId, timeline);
1093 }
1094
chaviwaf87b3e2019-10-01 16:59:28 -07001095 InputEvent* consume() {
1096 if (mInputReceiver == nullptr) {
1097 return nullptr;
1098 }
1099 return mInputReceiver->consume();
1100 }
1101
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001102 MotionEvent* consumeMotion() {
1103 InputEvent* event = consume();
1104 if (event == nullptr) {
1105 ADD_FAILURE() << "Consume failed : no event";
1106 return nullptr;
1107 }
1108 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1109 ADD_FAILURE() << "Instead of motion event, got "
1110 << inputEventTypeToString(event->getType());
1111 return nullptr;
1112 }
1113 return static_cast<MotionEvent*>(event);
1114 }
1115
Arthur Hungb92218b2018-08-14 12:00:21 +08001116 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001117 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001118 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001119 return; // Can't receive events if the window does not have input channel
1120 }
1121 ASSERT_NE(nullptr, mInputReceiver)
1122 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001123 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001124 }
1125
chaviwaf87b3e2019-10-01 16:59:28 -07001126 sp<IBinder> getToken() { return mInfo.token; }
1127
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001128 const std::string& getName() { return mName; }
1129
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001130 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1131 mInfo.ownerPid = ownerPid;
1132 mInfo.ownerUid = ownerUid;
1133 }
1134
chaviwd1c23182019-12-20 18:44:56 -08001135private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001136 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001137 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001138 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001139};
1140
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001141std::atomic<int32_t> FakeWindowHandle::sId{1};
1142
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001143static InputEventInjectionResult injectKey(
1144 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1145 int32_t displayId = ADISPLAY_ID_NONE,
1146 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001147 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1148 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001149 KeyEvent event;
1150 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1151
1152 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001153 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001154 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1155 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001156
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001157 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1158 if (!allowKeyRepeat) {
1159 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1160 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001161 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001162 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001163 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001164}
1165
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001166static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1167 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001168 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1169}
1170
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001171// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1172// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1173// has to be woken up to process the repeating key.
1174static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1175 int32_t displayId = ADISPLAY_ID_NONE) {
1176 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1177 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1178 /* allowKeyRepeat */ false);
1179}
1180
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001181static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1182 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001183 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1184}
1185
Garfield Tandf26e862020-07-01 20:18:19 -07001186class PointerBuilder {
1187public:
1188 PointerBuilder(int32_t id, int32_t toolType) {
1189 mProperties.clear();
1190 mProperties.id = id;
1191 mProperties.toolType = toolType;
1192 mCoords.clear();
1193 }
1194
1195 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1196
1197 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1198
1199 PointerBuilder& axis(int32_t axis, float value) {
1200 mCoords.setAxisValue(axis, value);
1201 return *this;
1202 }
1203
1204 PointerProperties buildProperties() const { return mProperties; }
1205
1206 PointerCoords buildCoords() const { return mCoords; }
1207
1208private:
1209 PointerProperties mProperties;
1210 PointerCoords mCoords;
1211};
1212
1213class MotionEventBuilder {
1214public:
1215 MotionEventBuilder(int32_t action, int32_t source) {
1216 mAction = action;
1217 mSource = source;
1218 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1219 }
1220
1221 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1222 mEventTime = eventTime;
1223 return *this;
1224 }
1225
1226 MotionEventBuilder& displayId(int32_t displayId) {
1227 mDisplayId = displayId;
1228 return *this;
1229 }
1230
1231 MotionEventBuilder& actionButton(int32_t actionButton) {
1232 mActionButton = actionButton;
1233 return *this;
1234 }
1235
arthurhung6d4bed92021-03-17 11:59:33 +08001236 MotionEventBuilder& buttonState(int32_t buttonState) {
1237 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001238 return *this;
1239 }
1240
1241 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1242 mRawXCursorPosition = rawXCursorPosition;
1243 return *this;
1244 }
1245
1246 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1247 mRawYCursorPosition = rawYCursorPosition;
1248 return *this;
1249 }
1250
1251 MotionEventBuilder& pointer(PointerBuilder pointer) {
1252 mPointers.push_back(pointer);
1253 return *this;
1254 }
1255
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001256 MotionEventBuilder& addFlag(uint32_t flags) {
1257 mFlags |= flags;
1258 return *this;
1259 }
1260
Garfield Tandf26e862020-07-01 20:18:19 -07001261 MotionEvent build() {
1262 std::vector<PointerProperties> pointerProperties;
1263 std::vector<PointerCoords> pointerCoords;
1264 for (const PointerBuilder& pointer : mPointers) {
1265 pointerProperties.push_back(pointer.buildProperties());
1266 pointerCoords.push_back(pointer.buildCoords());
1267 }
1268
1269 // Set mouse cursor position for the most common cases to avoid boilerplate.
1270 if (mSource == AINPUT_SOURCE_MOUSE &&
1271 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1272 mPointers.size() == 1) {
1273 mRawXCursorPosition = pointerCoords[0].getX();
1274 mRawYCursorPosition = pointerCoords[0].getY();
1275 }
1276
1277 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001278 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001279 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001280 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001281 mButtonState, MotionClassification::NONE, identityTransform,
1282 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07001283 mRawYCursorPosition, mDisplayOrientation, mDisplayWidth, mDisplayHeight,
1284 mEventTime, mEventTime, mPointers.size(), pointerProperties.data(),
1285 pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001286
1287 return event;
1288 }
1289
1290private:
1291 int32_t mAction;
1292 int32_t mSource;
1293 nsecs_t mEventTime;
1294 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1295 int32_t mActionButton{0};
1296 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001297 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001298 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1299 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
Evan Rosky09576692021-07-01 12:22:09 -07001300 uint32_t mDisplayOrientation{ui::Transform::ROT_0};
chaviw3277faf2021-05-19 16:45:23 -05001301 int32_t mDisplayWidth{INVALID_DISPLAY_SIZE};
1302 int32_t mDisplayHeight{INVALID_DISPLAY_SIZE};
Garfield Tandf26e862020-07-01 20:18:19 -07001303
1304 std::vector<PointerBuilder> mPointers;
1305};
1306
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001307static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001308 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1309 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001310 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001311 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1312 injectionTimeout,
1313 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1314}
1315
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001317 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1318 const PointF& position,
1319 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001320 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1321 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001322 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001323 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001324 MotionEvent event = MotionEventBuilder(action, source)
1325 .displayId(displayId)
1326 .eventTime(eventTime)
1327 .rawXCursorPosition(cursorPosition.x)
1328 .rawYCursorPosition(cursorPosition.y)
1329 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1330 .x(position.x)
1331 .y(position.y))
1332 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001333
1334 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001335 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001336}
1337
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001338static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1339 int32_t source, int32_t displayId,
1340 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001341 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001342}
1343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001344static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1345 int32_t source, int32_t displayId,
1346 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001347 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001348}
1349
Jackal Guof9696682018-10-05 12:23:23 +08001350static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1351 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1352 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001353 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1354 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1355 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001356
1357 return args;
1358}
1359
chaviwd1c23182019-12-20 18:44:56 -08001360static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1361 const std::vector<PointF>& points) {
1362 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001363 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1364 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1365 }
1366
chaviwd1c23182019-12-20 18:44:56 -08001367 PointerProperties pointerProperties[pointerCount];
1368 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001369
chaviwd1c23182019-12-20 18:44:56 -08001370 for (size_t i = 0; i < pointerCount; i++) {
1371 pointerProperties[i].clear();
1372 pointerProperties[i].id = i;
1373 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001374
chaviwd1c23182019-12-20 18:44:56 -08001375 pointerCoords[i].clear();
1376 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1377 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1378 }
Jackal Guof9696682018-10-05 12:23:23 +08001379
1380 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1381 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001382 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001383 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1384 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001385 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1386 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001387 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1388 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001389
1390 return args;
1391}
1392
chaviwd1c23182019-12-20 18:44:56 -08001393static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1394 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1395}
1396
Prabir Pradhanac483a62021-08-06 14:01:18 +00001397static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1398 const PointerCaptureRequest& request) {
1399 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001400}
1401
Arthur Hungb92218b2018-08-14 12:00:21 +08001402TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001404 sp<FakeWindowHandle> window =
1405 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001406
Arthur Hung72d8dc32020-03-28 00:48:39 +00001407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001411
1412 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001413 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001414}
1415
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001416/**
1417 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1418 * To ensure that window receives only events that were directly inside of it, add
1419 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1420 * when finding touched windows.
1421 * This test serves as a sanity check for the next test, where setInputWindows is
1422 * called twice.
1423 */
1424TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001425 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001426 sp<FakeWindowHandle> window =
1427 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1428 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001429 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001430
1431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001433 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1434 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001435 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001436
1437 // Window should receive motion event.
1438 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1439}
1440
1441/**
1442 * Calling setInputWindows twice, with the same info, should not cause any issues.
1443 * To ensure that window receives only events that were directly inside of it, add
1444 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1445 * when finding touched windows.
1446 */
1447TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001449 sp<FakeWindowHandle> window =
1450 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1451 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001452 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001453
1454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1458 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001460
1461 // Window should receive motion event.
1462 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1463}
1464
Arthur Hungb92218b2018-08-14 12:00:21 +08001465// The foreground window should receive the first touch down event.
1466TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001467 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001468 sp<FakeWindowHandle> windowTop =
1469 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1470 sp<FakeWindowHandle> windowSecond =
1471 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001472
Arthur Hung72d8dc32020-03-28 00:48:39 +00001473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1475 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1476 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001477
1478 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001479 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001480 windowSecond->assertNoEvents();
1481}
1482
Garfield Tandf26e862020-07-01 20:18:19 -07001483TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001484 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001485 sp<FakeWindowHandle> windowLeft =
1486 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1487 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001488 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001489 sp<FakeWindowHandle> windowRight =
1490 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1491 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001492 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001493
1494 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1495
1496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1497
1498 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001500 injectMotionEvent(mDispatcher,
1501 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1502 AINPUT_SOURCE_MOUSE)
1503 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1504 .x(900)
1505 .y(400))
1506 .build()));
1507 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1508 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1509 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1510 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1511
1512 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001513 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001514 injectMotionEvent(mDispatcher,
1515 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1516 AINPUT_SOURCE_MOUSE)
1517 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1518 .x(300)
1519 .y(400))
1520 .build()));
1521 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1522 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1523 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1524 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1525 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1526 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1527
1528 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001530 injectMotionEvent(mDispatcher,
1531 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1532 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1533 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1534 .x(300)
1535 .y(400))
1536 .build()));
1537 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1538
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001540 injectMotionEvent(mDispatcher,
1541 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1542 AINPUT_SOURCE_MOUSE)
1543 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1544 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1545 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1546 .x(300)
1547 .y(400))
1548 .build()));
1549 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1550 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1551
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001553 injectMotionEvent(mDispatcher,
1554 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1555 AINPUT_SOURCE_MOUSE)
1556 .buttonState(0)
1557 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1558 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1559 .x(300)
1560 .y(400))
1561 .build()));
1562 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1563 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1564
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001566 injectMotionEvent(mDispatcher,
1567 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1568 .buttonState(0)
1569 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1570 .x(300)
1571 .y(400))
1572 .build()));
1573 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1574
1575 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001577 injectMotionEvent(mDispatcher,
1578 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1579 AINPUT_SOURCE_MOUSE)
1580 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1581 .x(900)
1582 .y(400))
1583 .build()));
1584 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1585 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1586 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1587 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1588 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1589 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1590}
1591
1592// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1593// directly in this test.
1594TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001595 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001596 sp<FakeWindowHandle> window =
1597 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1598 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001599 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001600
1601 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1602
1603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1604
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001606 injectMotionEvent(mDispatcher,
1607 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1608 AINPUT_SOURCE_MOUSE)
1609 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1610 .x(300)
1611 .y(400))
1612 .build()));
1613 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1614 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1615
1616 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001618 injectMotionEvent(mDispatcher,
1619 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1620 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1621 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1622 .x(300)
1623 .y(400))
1624 .build()));
1625 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1626
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001628 injectMotionEvent(mDispatcher,
1629 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1630 AINPUT_SOURCE_MOUSE)
1631 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1632 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1633 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1634 .x(300)
1635 .y(400))
1636 .build()));
1637 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1638 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1639
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001641 injectMotionEvent(mDispatcher,
1642 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1643 AINPUT_SOURCE_MOUSE)
1644 .buttonState(0)
1645 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1646 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1647 .x(300)
1648 .y(400))
1649 .build()));
1650 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1651 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1652
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001654 injectMotionEvent(mDispatcher,
1655 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1656 .buttonState(0)
1657 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1658 .x(300)
1659 .y(400))
1660 .build()));
1661 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1662
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001664 injectMotionEvent(mDispatcher,
1665 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1666 AINPUT_SOURCE_MOUSE)
1667 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1668 .x(300)
1669 .y(400))
1670 .build()));
1671 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1672 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1673}
1674
Garfield Tan00f511d2019-06-12 16:55:40 -07001675TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001676 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001677
1678 sp<FakeWindowHandle> windowLeft =
1679 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1680 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001681 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001682 sp<FakeWindowHandle> windowRight =
1683 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1684 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001685 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001686
1687 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1688
Arthur Hung72d8dc32020-03-28 00:48:39 +00001689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001690
1691 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1692 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001694 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001695 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001696 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001697 windowRight->assertNoEvents();
1698}
1699
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001700TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001702 sp<FakeWindowHandle> window =
1703 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001704 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001705
Arthur Hung72d8dc32020-03-28 00:48:39 +00001706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001707 setFocusedWindow(window);
1708
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001709 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001710
1711 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1712 mDispatcher->notifyKey(&keyArgs);
1713
1714 // Window should receive key down event.
1715 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1716
1717 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1718 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001719 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001720 mDispatcher->notifyDeviceReset(&args);
1721 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1722 AKEY_EVENT_FLAG_CANCELED);
1723}
1724
1725TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001726 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001727 sp<FakeWindowHandle> window =
1728 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1729
Arthur Hung72d8dc32020-03-28 00:48:39 +00001730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001731
1732 NotifyMotionArgs motionArgs =
1733 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1734 ADISPLAY_ID_DEFAULT);
1735 mDispatcher->notifyMotion(&motionArgs);
1736
1737 // Window should receive motion down event.
1738 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1739
1740 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1741 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001742 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001743 mDispatcher->notifyDeviceReset(&args);
1744 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1745 0 /*expectedFlags*/);
1746}
1747
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001748using TransferFunction =
1749 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1750
1751class TransferTouchFixture : public InputDispatcherTest,
1752 public ::testing::WithParamInterface<TransferFunction> {};
1753
1754TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001756
1757 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001758 sp<FakeWindowHandle> firstWindow =
1759 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1760 sp<FakeWindowHandle> secondWindow =
1761 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001762
1763 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001765
1766 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001767 NotifyMotionArgs downMotionArgs =
1768 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1769 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001770 mDispatcher->notifyMotion(&downMotionArgs);
1771 // Only the first window should get the down event
1772 firstWindow->consumeMotionDown();
1773 secondWindow->assertNoEvents();
1774
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001775 // Transfer touch to the second window
1776 TransferFunction f = GetParam();
1777 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1778 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001779 // The first window gets cancel and the second gets down
1780 firstWindow->consumeMotionCancel();
1781 secondWindow->consumeMotionDown();
1782
1783 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001784 NotifyMotionArgs upMotionArgs =
1785 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1786 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001787 mDispatcher->notifyMotion(&upMotionArgs);
1788 // The first window gets no events and the second gets up
1789 firstWindow->assertNoEvents();
1790 secondWindow->consumeMotionUp();
1791}
1792
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001793TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001794 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001795
1796 PointF touchPoint = {10, 10};
1797
1798 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001799 sp<FakeWindowHandle> firstWindow =
1800 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1801 sp<FakeWindowHandle> secondWindow =
1802 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001803
1804 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001806
1807 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001808 NotifyMotionArgs downMotionArgs =
1809 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1810 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001811 mDispatcher->notifyMotion(&downMotionArgs);
1812 // Only the first window should get the down event
1813 firstWindow->consumeMotionDown();
1814 secondWindow->assertNoEvents();
1815
1816 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001817 NotifyMotionArgs pointerDownMotionArgs =
1818 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1819 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1820 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1821 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001822 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1823 // Only the first window should get the pointer down event
1824 firstWindow->consumeMotionPointerDown(1);
1825 secondWindow->assertNoEvents();
1826
1827 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001828 TransferFunction f = GetParam();
1829 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1830 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001831 // The first window gets cancel and the second gets down and pointer down
1832 firstWindow->consumeMotionCancel();
1833 secondWindow->consumeMotionDown();
1834 secondWindow->consumeMotionPointerDown(1);
1835
1836 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001837 NotifyMotionArgs pointerUpMotionArgs =
1838 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1839 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1840 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1841 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001842 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1843 // The first window gets nothing and the second gets pointer up
1844 firstWindow->assertNoEvents();
1845 secondWindow->consumeMotionPointerUp(1);
1846
1847 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001848 NotifyMotionArgs upMotionArgs =
1849 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1850 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001851 mDispatcher->notifyMotion(&upMotionArgs);
1852 // The first window gets nothing and the second gets up
1853 firstWindow->assertNoEvents();
1854 secondWindow->consumeMotionUp();
1855}
1856
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001857// For the cases of single pointer touch and two pointers non-split touch, the api's
1858// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1859// for the case where there are multiple pointers split across several windows.
1860INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1861 ::testing::Values(
1862 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
1863 sp<IBinder> destChannelToken) {
1864 return dispatcher->transferTouch(destChannelToken);
1865 },
1866 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
1867 sp<IBinder> to) {
1868 return dispatcher->transferTouchFocus(from, to,
1869 false /*isDragAndDrop*/);
1870 }));
1871
Svet Ganov5d3bc372020-01-26 23:11:07 -08001872TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001873 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001874
1875 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001876 sp<FakeWindowHandle> firstWindow =
1877 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001878 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001879 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001880
1881 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001882 sp<FakeWindowHandle> secondWindow =
1883 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001884 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001885 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001886
1887 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001889
1890 PointF pointInFirst = {300, 200};
1891 PointF pointInSecond = {300, 600};
1892
1893 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001894 NotifyMotionArgs firstDownMotionArgs =
1895 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1896 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001897 mDispatcher->notifyMotion(&firstDownMotionArgs);
1898 // Only the first window should get the down event
1899 firstWindow->consumeMotionDown();
1900 secondWindow->assertNoEvents();
1901
1902 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001903 NotifyMotionArgs secondDownMotionArgs =
1904 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1905 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1906 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1907 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001908 mDispatcher->notifyMotion(&secondDownMotionArgs);
1909 // The first window gets a move and the second a down
1910 firstWindow->consumeMotionMove();
1911 secondWindow->consumeMotionDown();
1912
1913 // Transfer touch focus to the second window
1914 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1915 // The first window gets cancel and the new gets pointer down (it already saw down)
1916 firstWindow->consumeMotionCancel();
1917 secondWindow->consumeMotionPointerDown(1);
1918
1919 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001920 NotifyMotionArgs pointerUpMotionArgs =
1921 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1922 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1923 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1924 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001925 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1926 // The first window gets nothing and the second gets pointer up
1927 firstWindow->assertNoEvents();
1928 secondWindow->consumeMotionPointerUp(1);
1929
1930 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001931 NotifyMotionArgs upMotionArgs =
1932 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1933 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001934 mDispatcher->notifyMotion(&upMotionArgs);
1935 // The first window gets nothing and the second gets up
1936 firstWindow->assertNoEvents();
1937 secondWindow->consumeMotionUp();
1938}
1939
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001940// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1941// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1942// touch is not supported, so the touch should continue on those windows and the transferred-to
1943// window should get nothing.
1944TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1945 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1946
1947 // Create a non touch modal window that supports split touch
1948 sp<FakeWindowHandle> firstWindow =
1949 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1950 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001951 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001952
1953 // Create a non touch modal window that supports split touch
1954 sp<FakeWindowHandle> secondWindow =
1955 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1956 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001957 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001958
1959 // Add the windows to the dispatcher
1960 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1961
1962 PointF pointInFirst = {300, 200};
1963 PointF pointInSecond = {300, 600};
1964
1965 // Send down to the first window
1966 NotifyMotionArgs firstDownMotionArgs =
1967 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1968 ADISPLAY_ID_DEFAULT, {pointInFirst});
1969 mDispatcher->notifyMotion(&firstDownMotionArgs);
1970 // Only the first window should get the down event
1971 firstWindow->consumeMotionDown();
1972 secondWindow->assertNoEvents();
1973
1974 // Send down to the second window
1975 NotifyMotionArgs secondDownMotionArgs =
1976 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1977 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1978 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1979 {pointInFirst, pointInSecond});
1980 mDispatcher->notifyMotion(&secondDownMotionArgs);
1981 // The first window gets a move and the second a down
1982 firstWindow->consumeMotionMove();
1983 secondWindow->consumeMotionDown();
1984
1985 // Transfer touch focus to the second window
1986 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1987 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1988 ASSERT_FALSE(transferred);
1989 firstWindow->assertNoEvents();
1990 secondWindow->assertNoEvents();
1991
1992 // The rest of the dispatch should proceed as normal
1993 // Send pointer up to the second window
1994 NotifyMotionArgs pointerUpMotionArgs =
1995 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1996 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1997 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1998 {pointInFirst, pointInSecond});
1999 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2000 // The first window gets MOVE and the second gets pointer up
2001 firstWindow->consumeMotionMove();
2002 secondWindow->consumeMotionUp();
2003
2004 // Send up event to the first window
2005 NotifyMotionArgs upMotionArgs =
2006 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2007 ADISPLAY_ID_DEFAULT);
2008 mDispatcher->notifyMotion(&upMotionArgs);
2009 // The first window gets nothing and the second gets up
2010 firstWindow->consumeMotionUp();
2011 secondWindow->assertNoEvents();
2012}
2013
Arthur Hungabbb9d82021-09-01 14:52:30 +00002014// This case will create two windows and one mirrored window on the default display and mirror
2015// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2016// the windows info of second display before default display.
2017TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2018 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2019 sp<FakeWindowHandle> firstWindowInPrimary =
2020 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2021 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2022 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2023 sp<FakeWindowHandle> secondWindowInPrimary =
2024 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2025 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2026 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2027
2028 sp<FakeWindowHandle> mirrorWindowInPrimary =
2029 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2030 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2031 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2032
2033 sp<FakeWindowHandle> firstWindowInSecondary =
2034 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2035 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2036 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2037
2038 sp<FakeWindowHandle> secondWindowInSecondary =
2039 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2040 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2041 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2042
2043 // Update window info, let it find window handle of second display first.
2044 mDispatcher->setInputWindows(
2045 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2046 {ADISPLAY_ID_DEFAULT,
2047 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2048
2049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2050 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2051 {50, 50}))
2052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2053
2054 // Window should receive motion event.
2055 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2056
2057 // Transfer touch focus
2058 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2059 secondWindowInPrimary->getToken()));
2060 // The first window gets cancel.
2061 firstWindowInPrimary->consumeMotionCancel();
2062 secondWindowInPrimary->consumeMotionDown();
2063
2064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2065 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2066 ADISPLAY_ID_DEFAULT, {150, 50}))
2067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2068 firstWindowInPrimary->assertNoEvents();
2069 secondWindowInPrimary->consumeMotionMove();
2070
2071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2072 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2073 {150, 50}))
2074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2075 firstWindowInPrimary->assertNoEvents();
2076 secondWindowInPrimary->consumeMotionUp();
2077}
2078
2079// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2080// 'transferTouch' api.
2081TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2082 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2083 sp<FakeWindowHandle> firstWindowInPrimary =
2084 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2085 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2086 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2087 sp<FakeWindowHandle> secondWindowInPrimary =
2088 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2089 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2090 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2091
2092 sp<FakeWindowHandle> mirrorWindowInPrimary =
2093 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2094 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2095 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2096
2097 sp<FakeWindowHandle> firstWindowInSecondary =
2098 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2099 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2100 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2101
2102 sp<FakeWindowHandle> secondWindowInSecondary =
2103 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2104 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2105 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2106
2107 // Update window info, let it find window handle of second display first.
2108 mDispatcher->setInputWindows(
2109 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2110 {ADISPLAY_ID_DEFAULT,
2111 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2112
2113 // Touch on second display.
2114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2117
2118 // Window should receive motion event.
2119 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2120
2121 // Transfer touch focus
2122 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2123
2124 // The first window gets cancel.
2125 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2126 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2127
2128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2129 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2130 SECOND_DISPLAY_ID, {150, 50}))
2131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2132 firstWindowInPrimary->assertNoEvents();
2133 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2134
2135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2136 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2138 firstWindowInPrimary->assertNoEvents();
2139 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2140}
2141
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002142TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002143 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002144 sp<FakeWindowHandle> window =
2145 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2146
Vishnu Nair47074b82020-08-14 11:54:47 -07002147 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002149 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002150
2151 window->consumeFocusEvent(true);
2152
2153 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2154 mDispatcher->notifyKey(&keyArgs);
2155
2156 // Window should receive key down event.
2157 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2158}
2159
2160TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002162 sp<FakeWindowHandle> window =
2163 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2164
Arthur Hung72d8dc32020-03-28 00:48:39 +00002165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002166
2167 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2168 mDispatcher->notifyKey(&keyArgs);
2169 mDispatcher->waitForIdle();
2170
2171 window->assertNoEvents();
2172}
2173
2174// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2175TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002176 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002177 sp<FakeWindowHandle> window =
2178 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2179
Arthur Hung72d8dc32020-03-28 00:48:39 +00002180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002181
2182 // Send key
2183 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2184 mDispatcher->notifyKey(&keyArgs);
2185 // Send motion
2186 NotifyMotionArgs motionArgs =
2187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2188 ADISPLAY_ID_DEFAULT);
2189 mDispatcher->notifyMotion(&motionArgs);
2190
2191 // Window should receive only the motion event
2192 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2193 window->assertNoEvents(); // Key event or focus event will not be received
2194}
2195
arthurhungea3f4fc2020-12-21 23:18:53 +08002196TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2197 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2198
2199 // Create first non touch modal window that supports split touch
2200 sp<FakeWindowHandle> firstWindow =
2201 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2202 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002203 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002204
2205 // Create second non touch modal window that supports split touch
2206 sp<FakeWindowHandle> secondWindow =
2207 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2208 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002209 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002210
2211 // Add the windows to the dispatcher
2212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2213
2214 PointF pointInFirst = {300, 200};
2215 PointF pointInSecond = {300, 600};
2216
2217 // Send down to the first window
2218 NotifyMotionArgs firstDownMotionArgs =
2219 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2220 ADISPLAY_ID_DEFAULT, {pointInFirst});
2221 mDispatcher->notifyMotion(&firstDownMotionArgs);
2222 // Only the first window should get the down event
2223 firstWindow->consumeMotionDown();
2224 secondWindow->assertNoEvents();
2225
2226 // Send down to the second window
2227 NotifyMotionArgs secondDownMotionArgs =
2228 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2229 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2230 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2231 {pointInFirst, pointInSecond});
2232 mDispatcher->notifyMotion(&secondDownMotionArgs);
2233 // The first window gets a move and the second a down
2234 firstWindow->consumeMotionMove();
2235 secondWindow->consumeMotionDown();
2236
2237 // Send pointer cancel to the second window
2238 NotifyMotionArgs pointerUpMotionArgs =
2239 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2240 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2241 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2242 {pointInFirst, pointInSecond});
2243 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2244 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2245 // The first window gets move and the second gets cancel.
2246 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2247 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2248
2249 // Send up event.
2250 NotifyMotionArgs upMotionArgs =
2251 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2252 ADISPLAY_ID_DEFAULT);
2253 mDispatcher->notifyMotion(&upMotionArgs);
2254 // The first window gets up and the second gets nothing.
2255 firstWindow->consumeMotionUp();
2256 secondWindow->assertNoEvents();
2257}
2258
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002259TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2261
2262 sp<FakeWindowHandle> window =
2263 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2265 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2266 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2267 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2268
2269 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2270 window->assertNoEvents();
2271 mDispatcher->waitForIdle();
2272}
2273
chaviwd1c23182019-12-20 18:44:56 -08002274class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002275public:
2276 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002277 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002278 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002279 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002280 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002281 }
2282
chaviwd1c23182019-12-20 18:44:56 -08002283 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2284
2285 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2286 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2287 expectedDisplayId, expectedFlags);
2288 }
2289
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002290 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2291
2292 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2293
chaviwd1c23182019-12-20 18:44:56 -08002294 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2295 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2296 expectedDisplayId, expectedFlags);
2297 }
2298
2299 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2300 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2301 expectedDisplayId, expectedFlags);
2302 }
2303
Evan Rosky84f07f02021-04-16 10:42:42 -07002304 MotionEvent* consumeMotion() {
2305 InputEvent* event = mInputReceiver->consume();
2306 if (!event) {
2307 ADD_FAILURE() << "No event was produced";
2308 return nullptr;
2309 }
2310 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2311 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2312 return nullptr;
2313 }
2314 return static_cast<MotionEvent*>(event);
2315 }
2316
chaviwd1c23182019-12-20 18:44:56 -08002317 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2318
2319private:
2320 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002321};
2322
2323// Tests for gesture monitors
2324TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002325 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002326 sp<FakeWindowHandle> window =
2327 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002329
chaviwd1c23182019-12-20 18:44:56 -08002330 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2331 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002332
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002334 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002336 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002337 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002338}
2339
2340TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002341 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002342 sp<FakeWindowHandle> window =
2343 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2344
2345 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002346 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002347
Arthur Hung72d8dc32020-03-28 00:48:39 +00002348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002349 setFocusedWindow(window);
2350
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002351 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002352
chaviwd1c23182019-12-20 18:44:56 -08002353 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2354 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002355
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002358 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002359 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002360}
2361
2362TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002363 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002364 sp<FakeWindowHandle> window =
2365 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002367
chaviwd1c23182019-12-20 18:44:56 -08002368 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2369 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002370
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002371 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002372 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002373 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002374 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002375 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002376
2377 window->releaseChannel();
2378
chaviwd1c23182019-12-20 18:44:56 -08002379 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002380
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002382 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002383 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002384 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002385}
2386
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002387TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2388 FakeMonitorReceiver monitor =
2389 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2390 true /*isGestureMonitor*/);
2391
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2394 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2395 ASSERT_TRUE(consumeSeq);
2396
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002397 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002398 monitor.finishEvent(*consumeSeq);
2399 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002400 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002401}
2402
Evan Rosky84f07f02021-04-16 10:42:42 -07002403// Tests for gesture monitors
2404TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2405 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2406 sp<FakeWindowHandle> window =
2407 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2409 window->setWindowOffset(20, 40);
2410 window->setWindowTransform(0, 1, -1, 0);
2411
2412 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2413 true /*isGestureMonitor*/);
2414
2415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2416 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2418 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2419 MotionEvent* event = monitor.consumeMotion();
2420 // Even though window has transform, gesture monitor must not.
2421 ASSERT_EQ(ui::Transform(), event->getTransform());
2422}
2423
chaviw81e2bb92019-12-18 15:03:51 -08002424TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002425 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002426 sp<FakeWindowHandle> window =
2427 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2428
Arthur Hung72d8dc32020-03-28 00:48:39 +00002429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002430
2431 NotifyMotionArgs motionArgs =
2432 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2433 ADISPLAY_ID_DEFAULT);
2434
2435 mDispatcher->notifyMotion(&motionArgs);
2436 // Window should receive motion down event.
2437 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2438
2439 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002440 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002441 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2442 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2443 motionArgs.pointerCoords[0].getX() - 10);
2444
2445 mDispatcher->notifyMotion(&motionArgs);
2446 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2447 0 /*expectedFlags*/);
2448}
2449
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002450/**
2451 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2452 * the device default right away. In the test scenario, we check both the default value,
2453 * and the action of enabling / disabling.
2454 */
2455TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002456 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002457 sp<FakeWindowHandle> window =
2458 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2459
2460 // Set focused application.
2461 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002462 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002463
2464 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002466 setFocusedWindow(window);
2467
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002468 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2469
2470 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002471 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002473 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2474
2475 SCOPED_TRACE("Disable touch mode");
2476 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002477 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002479 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002480 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2481
2482 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002483 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002485 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2486
2487 SCOPED_TRACE("Enable touch mode again");
2488 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002489 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002490 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002491 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002492 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2493
2494 window->assertNoEvents();
2495}
2496
Gang Wange9087892020-01-07 12:17:14 -05002497TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002498 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002499 sp<FakeWindowHandle> window =
2500 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2501
2502 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002503 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002504
Arthur Hung72d8dc32020-03-28 00:48:39 +00002505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002506 setFocusedWindow(window);
2507
Gang Wange9087892020-01-07 12:17:14 -05002508 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2509
2510 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2511 mDispatcher->notifyKey(&keyArgs);
2512
2513 InputEvent* event = window->consume();
2514 ASSERT_NE(event, nullptr);
2515
2516 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2517 ASSERT_NE(verified, nullptr);
2518 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2519
2520 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2521 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2522 ASSERT_EQ(keyArgs.source, verified->source);
2523 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2524
2525 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2526
2527 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2528 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002529 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2530 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2531 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2532 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2533 ASSERT_EQ(0, verifiedKey.repeatCount);
2534}
2535
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002536TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002538 sp<FakeWindowHandle> window =
2539 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2540
2541 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2542
Arthur Hung72d8dc32020-03-28 00:48:39 +00002543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002544
2545 NotifyMotionArgs motionArgs =
2546 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2547 ADISPLAY_ID_DEFAULT);
2548 mDispatcher->notifyMotion(&motionArgs);
2549
2550 InputEvent* event = window->consume();
2551 ASSERT_NE(event, nullptr);
2552
2553 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2554 ASSERT_NE(verified, nullptr);
2555 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2556
2557 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2558 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2559 EXPECT_EQ(motionArgs.source, verified->source);
2560 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2561
2562 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2563
2564 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2565 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2566 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2567 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2568 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2569 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2570 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2571}
2572
Prabir Pradhan664834b2021-05-20 16:00:42 -07002573TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002574 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2575 sp<FakeWindowHandle> window =
2576 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2577 const std::string name = window->getName();
2578
2579 // Window gets transformed by offset values.
2580 window->setWindowOffset(500.0f, 500.0f);
2581
2582 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2583 window->setFocusable(true);
2584
2585 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2586
2587 // First, we set focused window so that focusedWindowHandle is not null.
2588 setFocusedWindow(window);
2589
2590 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2591 window->consumeFocusEvent(true);
2592
Prabir Pradhan664834b2021-05-20 16:00:42 -07002593 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2594 AMOTION_EVENT_ACTION_DOWN),
2595 std::pair(AINPUT_SOURCE_JOYSTICK,
2596 AMOTION_EVENT_ACTION_MOVE)};
2597 for (const auto& [source, action] : nonTransformedSources) {
2598 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08002599 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002600
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002601 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08002602 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09002603
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002604 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07002605 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08002606 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002607
Prabir Pradhanbd527712021-03-09 19:17:09 -08002608 float expectedX = motionArgs.pointerCoords[0].getX();
2609 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002610
Prabir Pradhanbd527712021-03-09 19:17:09 -08002611 // Ensure the axis values from the final motion event are not transformed.
2612 EXPECT_EQ(expectedX, motionEvent.getX(0))
2613 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2614 << motionEvent.getX(0);
2615 EXPECT_EQ(expectedY, motionEvent.getY(0))
2616 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2617 << motionEvent.getY(0);
2618 // Ensure the raw and transformed axis values for the motion event are the same.
2619 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2620 << "expected raw and transformed X-axis values to be equal";
2621 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2622 << "expected raw and transformed Y-axis values to be equal";
2623 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002624}
2625
chaviw09c8d2d2020-08-24 15:48:26 -07002626/**
2627 * Ensure that separate calls to sign the same data are generating the same key.
2628 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2629 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2630 * tests.
2631 */
2632TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2633 KeyEvent event = getTestKeyEvent();
2634 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2635
2636 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2637 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2638 ASSERT_EQ(hmac1, hmac2);
2639}
2640
2641/**
2642 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2643 */
2644TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2645 KeyEvent event = getTestKeyEvent();
2646 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2647 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2648
2649 verifiedEvent.deviceId += 1;
2650 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2651
2652 verifiedEvent.source += 1;
2653 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2654
2655 verifiedEvent.eventTimeNanos += 1;
2656 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2657
2658 verifiedEvent.displayId += 1;
2659 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2660
2661 verifiedEvent.action += 1;
2662 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2663
2664 verifiedEvent.downTimeNanos += 1;
2665 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2666
2667 verifiedEvent.flags += 1;
2668 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2669
2670 verifiedEvent.keyCode += 1;
2671 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2672
2673 verifiedEvent.scanCode += 1;
2674 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2675
2676 verifiedEvent.metaState += 1;
2677 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2678
2679 verifiedEvent.repeatCount += 1;
2680 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2681}
2682
Vishnu Nair958da932020-08-21 17:12:37 -07002683TEST_F(InputDispatcherTest, SetFocusedWindow) {
2684 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2685 sp<FakeWindowHandle> windowTop =
2686 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2687 sp<FakeWindowHandle> windowSecond =
2688 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2689 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2690
2691 // Top window is also focusable but is not granted focus.
2692 windowTop->setFocusable(true);
2693 windowSecond->setFocusable(true);
2694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2695 setFocusedWindow(windowSecond);
2696
2697 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2699 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002700
2701 // Focused window should receive event.
2702 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2703 windowTop->assertNoEvents();
2704}
2705
2706TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2707 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2708 sp<FakeWindowHandle> window =
2709 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2710 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2711
2712 window->setFocusable(true);
2713 // Release channel for window is no longer valid.
2714 window->releaseChannel();
2715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2716 setFocusedWindow(window);
2717
2718 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002719 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2720 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002721
2722 // window channel is invalid, so it should not receive any input event.
2723 window->assertNoEvents();
2724}
2725
2726TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2727 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2728 sp<FakeWindowHandle> window =
2729 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2730 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2731
2732 // Window is not focusable.
2733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2734 setFocusedWindow(window);
2735
2736 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002737 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2738 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002739
2740 // window is invalid, so it should not receive any input event.
2741 window->assertNoEvents();
2742}
2743
2744TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2745 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2746 sp<FakeWindowHandle> windowTop =
2747 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2748 sp<FakeWindowHandle> windowSecond =
2749 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2750 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2751
2752 windowTop->setFocusable(true);
2753 windowSecond->setFocusable(true);
2754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2755 setFocusedWindow(windowTop);
2756 windowTop->consumeFocusEvent(true);
2757
2758 setFocusedWindow(windowSecond, windowTop);
2759 windowSecond->consumeFocusEvent(true);
2760 windowTop->consumeFocusEvent(false);
2761
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2763 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002764
2765 // Focused window should receive event.
2766 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2767}
2768
2769TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2771 sp<FakeWindowHandle> windowTop =
2772 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2773 sp<FakeWindowHandle> windowSecond =
2774 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2775 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2776
2777 windowTop->setFocusable(true);
2778 windowSecond->setFocusable(true);
2779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2780 setFocusedWindow(windowSecond, windowTop);
2781
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002782 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2783 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002784
2785 // Event should be dropped.
2786 windowTop->assertNoEvents();
2787 windowSecond->assertNoEvents();
2788}
2789
2790TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2791 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2792 sp<FakeWindowHandle> window =
2793 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2794 sp<FakeWindowHandle> previousFocusedWindow =
2795 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2796 ADISPLAY_ID_DEFAULT);
2797 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2798
2799 window->setFocusable(true);
2800 previousFocusedWindow->setFocusable(true);
2801 window->setVisible(false);
2802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2803 setFocusedWindow(previousFocusedWindow);
2804 previousFocusedWindow->consumeFocusEvent(true);
2805
2806 // Requesting focus on invisible window takes focus from currently focused window.
2807 setFocusedWindow(window);
2808 previousFocusedWindow->consumeFocusEvent(false);
2809
2810 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002812 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002813 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002814
2815 // Window does not get focus event or key down.
2816 window->assertNoEvents();
2817
2818 // Window becomes visible.
2819 window->setVisible(true);
2820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2821
2822 // Window receives focus event.
2823 window->consumeFocusEvent(true);
2824 // Focused window receives key down.
2825 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2826}
2827
Vishnu Nair599f1412021-06-21 10:39:58 -07002828TEST_F(InputDispatcherTest, DisplayRemoved) {
2829 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2830 sp<FakeWindowHandle> window =
2831 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
2832 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2833
2834 // window is granted focus.
2835 window->setFocusable(true);
2836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2837 setFocusedWindow(window);
2838 window->consumeFocusEvent(true);
2839
2840 // When a display is removed window loses focus.
2841 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
2842 window->consumeFocusEvent(false);
2843}
2844
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002845/**
2846 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2847 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2848 * of the 'slipperyEnterWindow'.
2849 *
2850 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2851 * a way so that the touched location is no longer covered by the top window.
2852 *
2853 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2854 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2855 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2856 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2857 * with ACTION_DOWN).
2858 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2859 * window moved itself away from the touched location and had Flag::SLIPPERY.
2860 *
2861 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2862 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2863 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2864 *
2865 * In this test, we ensure that the event received by the bottom window has
2866 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2867 */
2868TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2869 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2870 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2871
2872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2873 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2874
2875 sp<FakeWindowHandle> slipperyExitWindow =
2876 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05002877 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002878 // Make sure this one overlaps the bottom window
2879 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2880 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2881 // one. Windows with the same owner are not considered to be occluding each other.
2882 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2883
2884 sp<FakeWindowHandle> slipperyEnterWindow =
2885 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2886 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2887
2888 mDispatcher->setInputWindows(
2889 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2890
2891 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2892 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2893 ADISPLAY_ID_DEFAULT, {{50, 50}});
2894 mDispatcher->notifyMotion(&args);
2895 slipperyExitWindow->consumeMotionDown();
2896 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2897 mDispatcher->setInputWindows(
2898 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2899
2900 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2901 ADISPLAY_ID_DEFAULT, {{51, 51}});
2902 mDispatcher->notifyMotion(&args);
2903
2904 slipperyExitWindow->consumeMotionCancel();
2905
2906 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2907 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2908}
2909
Garfield Tan1c7bc862020-01-28 13:24:04 -08002910class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2911protected:
2912 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2913 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2914
Chris Yea209fde2020-07-22 13:54:51 -07002915 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002916 sp<FakeWindowHandle> mWindow;
2917
2918 virtual void SetUp() override {
2919 mFakePolicy = new FakeInputDispatcherPolicy();
2920 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2921 mDispatcher = new InputDispatcher(mFakePolicy);
2922 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2923 ASSERT_EQ(OK, mDispatcher->start());
2924
2925 setUpWindow();
2926 }
2927
2928 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002929 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002930 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2931
Vishnu Nair47074b82020-08-14 11:54:47 -07002932 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002934 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002935 mWindow->consumeFocusEvent(true);
2936 }
2937
Chris Ye2ad95392020-09-01 13:44:44 -07002938 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002939 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002940 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002941 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2942 mDispatcher->notifyKey(&keyArgs);
2943
2944 // Window should receive key down event.
2945 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2946 }
2947
2948 void expectKeyRepeatOnce(int32_t repeatCount) {
2949 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2950 InputEvent* repeatEvent = mWindow->consume();
2951 ASSERT_NE(nullptr, repeatEvent);
2952
2953 uint32_t eventType = repeatEvent->getType();
2954 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2955
2956 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2957 uint32_t eventAction = repeatKeyEvent->getAction();
2958 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2959 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2960 }
2961
Chris Ye2ad95392020-09-01 13:44:44 -07002962 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002963 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002964 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002965 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2966 mDispatcher->notifyKey(&keyArgs);
2967
2968 // Window should receive key down event.
2969 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2970 0 /*expectedFlags*/);
2971 }
2972};
2973
2974TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002975 sendAndConsumeKeyDown(1 /* deviceId */);
2976 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2977 expectKeyRepeatOnce(repeatCount);
2978 }
2979}
2980
2981TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2982 sendAndConsumeKeyDown(1 /* deviceId */);
2983 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2984 expectKeyRepeatOnce(repeatCount);
2985 }
2986 sendAndConsumeKeyDown(2 /* deviceId */);
2987 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002988 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2989 expectKeyRepeatOnce(repeatCount);
2990 }
2991}
2992
2993TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002994 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002995 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002996 sendAndConsumeKeyUp(1 /* deviceId */);
2997 mWindow->assertNoEvents();
2998}
2999
3000TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3001 sendAndConsumeKeyDown(1 /* deviceId */);
3002 expectKeyRepeatOnce(1 /*repeatCount*/);
3003 sendAndConsumeKeyDown(2 /* deviceId */);
3004 expectKeyRepeatOnce(1 /*repeatCount*/);
3005 // Stale key up from device 1.
3006 sendAndConsumeKeyUp(1 /* deviceId */);
3007 // Device 2 is still down, keep repeating
3008 expectKeyRepeatOnce(2 /*repeatCount*/);
3009 expectKeyRepeatOnce(3 /*repeatCount*/);
3010 // Device 2 key up
3011 sendAndConsumeKeyUp(2 /* deviceId */);
3012 mWindow->assertNoEvents();
3013}
3014
3015TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3016 sendAndConsumeKeyDown(1 /* deviceId */);
3017 expectKeyRepeatOnce(1 /*repeatCount*/);
3018 sendAndConsumeKeyDown(2 /* deviceId */);
3019 expectKeyRepeatOnce(1 /*repeatCount*/);
3020 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3021 sendAndConsumeKeyUp(2 /* deviceId */);
3022 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003023 mWindow->assertNoEvents();
3024}
3025
3026TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003027 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003028 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3029 InputEvent* repeatEvent = mWindow->consume();
3030 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3031 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3032 IdGenerator::getSource(repeatEvent->getId()));
3033 }
3034}
3035
3036TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003037 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003038
3039 std::unordered_set<int32_t> idSet;
3040 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3041 InputEvent* repeatEvent = mWindow->consume();
3042 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3043 int32_t id = repeatEvent->getId();
3044 EXPECT_EQ(idSet.end(), idSet.find(id));
3045 idSet.insert(id);
3046 }
3047}
3048
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003049/* Test InputDispatcher for MultiDisplay */
3050class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3051public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003052 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003053 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003054
Chris Yea209fde2020-07-22 13:54:51 -07003055 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003056 windowInPrimary =
3057 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003058
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003059 // Set focus window for primary display, but focused display would be second one.
3060 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003061 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003062 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003063 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003064 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003065
Chris Yea209fde2020-07-22 13:54:51 -07003066 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003067 windowInSecondary =
3068 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003069 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003070 // Set focus display to second one.
3071 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3072 // Set focus window for second display.
3073 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003074 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003075 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003076 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003077 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003078 }
3079
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003080 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003081 InputDispatcherTest::TearDown();
3082
Chris Yea209fde2020-07-22 13:54:51 -07003083 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003084 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003085 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003086 windowInSecondary.clear();
3087 }
3088
3089protected:
Chris Yea209fde2020-07-22 13:54:51 -07003090 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003091 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003092 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003093 sp<FakeWindowHandle> windowInSecondary;
3094};
3095
3096TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3097 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3099 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003101 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003102 windowInSecondary->assertNoEvents();
3103
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003104 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3106 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3107 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003108 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003109 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003110}
3111
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003112TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003113 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3115 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003116 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003117 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003118 windowInSecondary->assertNoEvents();
3119
3120 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003121 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003122 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003123 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003124 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003125
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003126 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003127 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003128
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003129 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003130 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3131 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003132
3133 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003134 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003135 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003136 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003137 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003138 windowInSecondary->assertNoEvents();
3139}
3140
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003141// Test per-display input monitors for motion event.
3142TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003143 FakeMonitorReceiver monitorInPrimary =
3144 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3145 FakeMonitorReceiver monitorInSecondary =
3146 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003147
3148 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003149 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3150 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3151 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003152 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003153 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003154 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003155 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003156
3157 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3159 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3160 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003161 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003162 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003163 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003164 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003165
3166 // Test inject a non-pointer motion event.
3167 // If specific a display, it will dispatch to the focused window of particular display,
3168 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003169 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3170 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3171 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003172 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003173 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003174 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003175 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003176}
3177
3178// Test per-display input monitors for key event.
3179TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003180 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003181 FakeMonitorReceiver monitorInPrimary =
3182 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3183 FakeMonitorReceiver monitorInSecondary =
3184 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003185
3186 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3188 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003189 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003190 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003191 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003192 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003193}
3194
Vishnu Nair958da932020-08-21 17:12:37 -07003195TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3196 sp<FakeWindowHandle> secondWindowInPrimary =
3197 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3198 secondWindowInPrimary->setFocusable(true);
3199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3200 setFocusedWindow(secondWindowInPrimary);
3201 windowInPrimary->consumeFocusEvent(false);
3202 secondWindowInPrimary->consumeFocusEvent(true);
3203
3204 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3206 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003207 windowInPrimary->assertNoEvents();
3208 windowInSecondary->assertNoEvents();
3209 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3210}
3211
Jackal Guof9696682018-10-05 12:23:23 +08003212class InputFilterTest : public InputDispatcherTest {
3213protected:
Jackal Guof9696682018-10-05 12:23:23 +08003214 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3215 NotifyMotionArgs motionArgs;
3216
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003217 motionArgs =
3218 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003219 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003220 motionArgs =
3221 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003222 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003223 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003224 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003225 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003226 } else {
3227 mFakePolicy->assertFilterInputEventWasNotCalled();
3228 }
3229 }
3230
3231 void testNotifyKey(bool expectToBeFiltered) {
3232 NotifyKeyArgs keyArgs;
3233
3234 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3235 mDispatcher->notifyKey(&keyArgs);
3236 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3237 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003238 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003239
3240 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003241 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003242 } else {
3243 mFakePolicy->assertFilterInputEventWasNotCalled();
3244 }
3245 }
3246};
3247
3248// Test InputFilter for MotionEvent
3249TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3250 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3251 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3252 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3253
3254 // Enable InputFilter
3255 mDispatcher->setInputFilterEnabled(true);
3256 // Test touch on both primary and second display, and check if both events are filtered.
3257 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3258 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3259
3260 // Disable InputFilter
3261 mDispatcher->setInputFilterEnabled(false);
3262 // Test touch on both primary and second display, and check if both events aren't filtered.
3263 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3264 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3265}
3266
3267// Test InputFilter for KeyEvent
3268TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3269 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3270 testNotifyKey(/*expectToBeFiltered*/ false);
3271
3272 // Enable InputFilter
3273 mDispatcher->setInputFilterEnabled(true);
3274 // Send a key event, and check if it is filtered.
3275 testNotifyKey(/*expectToBeFiltered*/ true);
3276
3277 // Disable InputFilter
3278 mDispatcher->setInputFilterEnabled(false);
3279 // Send a key event, and check if it isn't filtered.
3280 testNotifyKey(/*expectToBeFiltered*/ false);
3281}
3282
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003283class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3284protected:
3285 virtual void SetUp() override {
3286 InputDispatcherTest::SetUp();
3287
3288 /**
3289 * We don't need to enable input filter to test the injected event policy, but we enabled it
3290 * here to make the tests more realistic, since this policy only matters when inputfilter is
3291 * on.
3292 */
3293 mDispatcher->setInputFilterEnabled(true);
3294
3295 std::shared_ptr<InputApplicationHandle> application =
3296 std::make_shared<FakeApplicationHandle>();
3297 mWindow =
3298 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3299
3300 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3301 mWindow->setFocusable(true);
3302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3303 setFocusedWindow(mWindow);
3304 mWindow->consumeFocusEvent(true);
3305 }
3306
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003307 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3308 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003309 KeyEvent event;
3310
3311 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3312 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3313 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3314 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3315 const int32_t additionalPolicyFlags =
3316 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3318 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3319 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3320 policyFlags | additionalPolicyFlags));
3321
3322 InputEvent* received = mWindow->consume();
3323 ASSERT_NE(nullptr, received);
3324 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003325 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3326 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3327 ASSERT_EQ(flags, keyEvent.getFlags());
3328 }
3329
3330 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3331 int32_t flags) {
3332 MotionEvent event;
3333 PointerProperties pointerProperties[1];
3334 PointerCoords pointerCoords[1];
3335 pointerProperties[0].clear();
3336 pointerProperties[0].id = 0;
3337 pointerCoords[0].clear();
3338 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3339 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3340
3341 ui::Transform identityTransform;
3342 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3343 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3344 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3345 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3346 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -07003347 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
3348 0 /*INVALID_DISPLAY_SIZE*/, 0 /*INVALID_DISPLAY_SIZE*/, eventTime,
3349 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003350 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3351
3352 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3354 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3355 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3356 policyFlags | additionalPolicyFlags));
3357
3358 InputEvent* received = mWindow->consume();
3359 ASSERT_NE(nullptr, received);
3360 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3361 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3362 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3363 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003364 }
3365
3366private:
3367 sp<FakeWindowHandle> mWindow;
3368};
3369
3370TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003371 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3372 // filter. Without it, the event will no different from a regularly injected event, and the
3373 // injected device id will be overwritten.
3374 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3375 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003376}
3377
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003378TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003379 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003380 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3381 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3382}
3383
3384TEST_F(InputFilterInjectionPolicyTest,
3385 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3386 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3387 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3388 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003389}
3390
3391TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3392 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003393 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003394}
3395
chaviwfd6d3512019-03-25 13:23:49 -07003396class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003397 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003398 InputDispatcherTest::SetUp();
3399
Chris Yea209fde2020-07-22 13:54:51 -07003400 std::shared_ptr<FakeApplicationHandle> application =
3401 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003402 mUnfocusedWindow =
3403 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003404 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3405 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3406 // window.
chaviw3277faf2021-05-19 16:45:23 -05003407 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003408
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003409 mFocusedWindow =
3410 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3411 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003412 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003413
3414 // Set focused application.
3415 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003416 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003417
3418 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003420 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003421 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003422 }
3423
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003424 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003425 InputDispatcherTest::TearDown();
3426
3427 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003428 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003429 }
3430
3431protected:
3432 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003433 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003434 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003435};
3436
3437// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3438// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3439// the onPointerDownOutsideFocus callback.
3440TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003442 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3443 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003444 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003445 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003446
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003447 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003448 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3449}
3450
3451// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3452// DOWN on the window that doesn't have focus. Ensure no window received the
3453// onPointerDownOutsideFocus callback.
3454TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003456 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003458 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003459
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003460 ASSERT_TRUE(mDispatcher->waitForIdle());
3461 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003462}
3463
3464// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3465// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3466TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3468 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003469 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003470 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003471
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003472 ASSERT_TRUE(mDispatcher->waitForIdle());
3473 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003474}
3475
3476// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3477// DOWN on the window that already has focus. Ensure no window received the
3478// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003479TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003481 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003482 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003483 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003484 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003485
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003486 ASSERT_TRUE(mDispatcher->waitForIdle());
3487 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003488}
3489
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003490// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3491// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3492TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3493 const MotionEvent event =
3494 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3495 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3496 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3497 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3498 .build();
3499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3500 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3501 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3502
3503 ASSERT_TRUE(mDispatcher->waitForIdle());
3504 mFakePolicy->assertOnPointerDownWasNotCalled();
3505 // Ensure that the unfocused window did not receive any FOCUS events.
3506 mUnfocusedWindow->assertNoEvents();
3507}
3508
chaviwaf87b3e2019-10-01 16:59:28 -07003509// These tests ensures we can send touch events to a single client when there are multiple input
3510// windows that point to the same client token.
3511class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3512 virtual void SetUp() override {
3513 InputDispatcherTest::SetUp();
3514
Chris Yea209fde2020-07-22 13:54:51 -07003515 std::shared_ptr<FakeApplicationHandle> application =
3516 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003517 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3518 ADISPLAY_ID_DEFAULT);
3519 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3520 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003521 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003522 mWindow1->setFrame(Rect(0, 0, 100, 100));
3523
3524 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3525 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003526 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003527 mWindow2->setFrame(Rect(100, 100, 200, 200));
3528
Arthur Hung72d8dc32020-03-28 00:48:39 +00003529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003530 }
3531
3532protected:
3533 sp<FakeWindowHandle> mWindow1;
3534 sp<FakeWindowHandle> mWindow2;
3535
3536 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003537 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003538 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3539 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003540 }
3541
3542 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3543 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003544 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003545 InputEvent* event = window->consume();
3546
3547 ASSERT_NE(nullptr, event) << name.c_str()
3548 << ": consumer should have returned non-NULL event.";
3549
3550 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3551 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3552 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3553
3554 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3555 EXPECT_EQ(expectedAction, motionEvent.getAction());
3556
3557 for (size_t i = 0; i < points.size(); i++) {
3558 float expectedX = points[i].x;
3559 float expectedY = points[i].y;
3560
3561 EXPECT_EQ(expectedX, motionEvent.getX(i))
3562 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3563 << ", got " << motionEvent.getX(i);
3564 EXPECT_EQ(expectedY, motionEvent.getY(i))
3565 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3566 << ", got " << motionEvent.getY(i);
3567 }
3568 }
chaviw9eaa22c2020-07-01 16:21:27 -07003569
3570 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3571 std::vector<PointF> expectedPoints) {
3572 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3573 ADISPLAY_ID_DEFAULT, touchedPoints);
3574 mDispatcher->notifyMotion(&motionArgs);
3575
3576 // Always consume from window1 since it's the window that has the InputReceiver
3577 consumeMotionEvent(mWindow1, action, expectedPoints);
3578 }
chaviwaf87b3e2019-10-01 16:59:28 -07003579};
3580
3581TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3582 // Touch Window 1
3583 PointF touchedPoint = {10, 10};
3584 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003585 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003586
3587 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003588 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003589
3590 // Touch Window 2
3591 touchedPoint = {150, 150};
3592 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003593 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003594}
3595
chaviw9eaa22c2020-07-01 16:21:27 -07003596TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3597 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003598 mWindow2->setWindowScale(0.5f, 0.5f);
3599
3600 // Touch Window 1
3601 PointF touchedPoint = {10, 10};
3602 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003603 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003604 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003605 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003606
3607 // Touch Window 2
3608 touchedPoint = {150, 150};
3609 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003610 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3611 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003612
chaviw9eaa22c2020-07-01 16:21:27 -07003613 // Update the transform so rotation is set
3614 mWindow2->setWindowTransform(0, -1, 1, 0);
3615 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3616 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003617}
3618
chaviw9eaa22c2020-07-01 16:21:27 -07003619TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003620 mWindow2->setWindowScale(0.5f, 0.5f);
3621
3622 // Touch Window 1
3623 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3624 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003625 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003626
3627 // Touch Window 2
3628 int32_t actionPointerDown =
3629 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003630 touchedPoints.push_back(PointF{150, 150});
3631 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3632 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003633
chaviw9eaa22c2020-07-01 16:21:27 -07003634 // Release Window 2
3635 int32_t actionPointerUp =
3636 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3637 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3638 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003639
chaviw9eaa22c2020-07-01 16:21:27 -07003640 // Update the transform so rotation is set for Window 2
3641 mWindow2->setWindowTransform(0, -1, 1, 0);
3642 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3643 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003644}
3645
chaviw9eaa22c2020-07-01 16:21:27 -07003646TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003647 mWindow2->setWindowScale(0.5f, 0.5f);
3648
3649 // Touch Window 1
3650 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3651 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003652 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003653
3654 // Touch Window 2
3655 int32_t actionPointerDown =
3656 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003657 touchedPoints.push_back(PointF{150, 150});
3658 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003659
chaviw9eaa22c2020-07-01 16:21:27 -07003660 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003661
3662 // Move both windows
3663 touchedPoints = {{20, 20}, {175, 175}};
3664 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3665 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3666
chaviw9eaa22c2020-07-01 16:21:27 -07003667 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003668
chaviw9eaa22c2020-07-01 16:21:27 -07003669 // Release Window 2
3670 int32_t actionPointerUp =
3671 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3672 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3673 expectedPoints.pop_back();
3674
3675 // Touch Window 2
3676 mWindow2->setWindowTransform(0, -1, 1, 0);
3677 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3678 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3679
3680 // Move both windows
3681 touchedPoints = {{20, 20}, {175, 175}};
3682 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3683 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3684
3685 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003686}
3687
3688TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3689 mWindow1->setWindowScale(0.5f, 0.5f);
3690
3691 // Touch Window 1
3692 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3693 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003694 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003695
3696 // Touch Window 2
3697 int32_t actionPointerDown =
3698 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003699 touchedPoints.push_back(PointF{150, 150});
3700 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003701
chaviw9eaa22c2020-07-01 16:21:27 -07003702 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003703
3704 // Move both windows
3705 touchedPoints = {{20, 20}, {175, 175}};
3706 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3707 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3708
chaviw9eaa22c2020-07-01 16:21:27 -07003709 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003710}
3711
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003712class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3713 virtual void SetUp() override {
3714 InputDispatcherTest::SetUp();
3715
Chris Yea209fde2020-07-22 13:54:51 -07003716 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003717 mApplication->setDispatchingTimeout(20ms);
3718 mWindow =
3719 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3720 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003721 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003722 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003723 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3724 // window.
chaviw3277faf2021-05-19 16:45:23 -05003725 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003726
3727 // Set focused application.
3728 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3729
3730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003731 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003732 mWindow->consumeFocusEvent(true);
3733 }
3734
3735 virtual void TearDown() override {
3736 InputDispatcherTest::TearDown();
3737 mWindow.clear();
3738 }
3739
3740protected:
Chris Yea209fde2020-07-22 13:54:51 -07003741 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003742 sp<FakeWindowHandle> mWindow;
3743 static constexpr PointF WINDOW_LOCATION = {20, 20};
3744
3745 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003747 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3748 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003750 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3751 WINDOW_LOCATION));
3752 }
3753};
3754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003755// Send a tap and respond, which should not cause an ANR.
3756TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3757 tapOnWindow();
3758 mWindow->consumeMotionDown();
3759 mWindow->consumeMotionUp();
3760 ASSERT_TRUE(mDispatcher->waitForIdle());
3761 mFakePolicy->assertNotifyAnrWasNotCalled();
3762}
3763
3764// Send a regular key and respond, which should not cause an ANR.
3765TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003767 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3768 ASSERT_TRUE(mDispatcher->waitForIdle());
3769 mFakePolicy->assertNotifyAnrWasNotCalled();
3770}
3771
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003772TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3773 mWindow->setFocusable(false);
3774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3775 mWindow->consumeFocusEvent(false);
3776
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003777 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003778 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003779 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3780 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003782 // Key will not go to window because we have no focused window.
3783 // The 'no focused window' ANR timer should start instead.
3784
3785 // Now, the focused application goes away.
3786 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3787 // The key should get dropped and there should be no ANR.
3788
3789 ASSERT_TRUE(mDispatcher->waitForIdle());
3790 mFakePolicy->assertNotifyAnrWasNotCalled();
3791}
3792
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003793// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003794// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3795// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003796TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003798 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3799 WINDOW_LOCATION));
3800
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003801 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3802 ASSERT_TRUE(sequenceNum);
3803 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003804 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003805
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003806 mWindow->finishEvent(*sequenceNum);
3807 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3808 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003809 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003810 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003811}
3812
3813// Send a key to the app and have the app not respond right away.
3814TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3815 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003817 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3818 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003819 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003820 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003821 ASSERT_TRUE(mDispatcher->waitForIdle());
3822}
3823
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003824// We have a focused application, but no focused window
3825TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003826 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3828 mWindow->consumeFocusEvent(false);
3829
3830 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003832 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3833 WINDOW_LOCATION));
3834 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3835 mDispatcher->waitForIdle();
3836 mFakePolicy->assertNotifyAnrWasNotCalled();
3837
3838 // Once a focused event arrives, we get an ANR for this application
3839 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3840 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003841 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003842 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003843 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003844 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003845 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003846 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003847 ASSERT_TRUE(mDispatcher->waitForIdle());
3848}
3849
3850// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003851// Make sure that we don't notify policy twice about the same ANR.
3852TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003853 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3855 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003856
3857 // Once a focused event arrives, we get an ANR for this application
3858 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3859 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003860 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003861 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003862 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003863 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003864 const std::chrono::duration appTimeout =
3865 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003866 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003867
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003868 std::this_thread::sleep_for(appTimeout);
3869 // ANR should not be raised again. It is up to policy to do that if it desires.
3870 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003871
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003872 // If we now get a focused window, the ANR should stop, but the policy handles that via
3873 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003874 ASSERT_TRUE(mDispatcher->waitForIdle());
3875}
3876
3877// We have a focused application, but no focused window
3878TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003879 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3881 mWindow->consumeFocusEvent(false);
3882
3883 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003884 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003885 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003886 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3887 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003888
3889 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003890 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003891
3892 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003893 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003894 ASSERT_TRUE(mDispatcher->waitForIdle());
3895 mWindow->assertNoEvents();
3896}
3897
3898/**
3899 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3900 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3901 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3902 * the ANR mechanism should still work.
3903 *
3904 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3905 * DOWN event, while not responding on the second one.
3906 */
3907TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3908 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3909 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3910 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3911 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3912 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003913 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003914
3915 // Now send ACTION_UP, with identical timestamp
3916 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3917 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3918 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3919 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003920 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003921
3922 // We have now sent down and up. Let's consume first event and then ANR on the second.
3923 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3924 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003925 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003926}
3927
3928// If an app is not responding to a key event, gesture monitors should continue to receive
3929// new motion events
3930TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3931 FakeMonitorReceiver monitor =
3932 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3933 true /*isGestureMonitor*/);
3934
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3936 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003937 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003939
3940 // Stuck on the ACTION_UP
3941 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003942 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003943
3944 // New tap will go to the gesture monitor, but not to the window
3945 tapOnWindow();
3946 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3947 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3948
3949 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3950 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003951 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003952 mWindow->assertNoEvents();
3953 monitor.assertNoEvents();
3954}
3955
3956// If an app is not responding to a motion event, gesture monitors should continue to receive
3957// new motion events
3958TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3959 FakeMonitorReceiver monitor =
3960 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3961 true /*isGestureMonitor*/);
3962
3963 tapOnWindow();
3964 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3965 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3966
3967 mWindow->consumeMotionDown();
3968 // Stuck on the ACTION_UP
3969 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003970 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003971
3972 // New tap will go to the gesture monitor, but not to the window
3973 tapOnWindow();
3974 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3975 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3976
3977 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3978 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003979 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003980 mWindow->assertNoEvents();
3981 monitor.assertNoEvents();
3982}
3983
3984// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3985// process events, you don't get an anr. When the window later becomes unresponsive again, you
3986// get an ANR again.
3987// 1. tap -> block on ACTION_UP -> receive ANR
3988// 2. consume all pending events (= queue becomes healthy again)
3989// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3990TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3991 tapOnWindow();
3992
3993 mWindow->consumeMotionDown();
3994 // Block on ACTION_UP
3995 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003996 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003997 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3998 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003999 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004000 mWindow->assertNoEvents();
4001
4002 tapOnWindow();
4003 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004004 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004005 mWindow->consumeMotionUp();
4006
4007 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004008 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004009 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004010 mWindow->assertNoEvents();
4011}
4012
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004013// If a connection remains unresponsive for a while, make sure policy is only notified once about
4014// it.
4015TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004017 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4018 WINDOW_LOCATION));
4019
4020 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004021 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004022 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004023 // 'notifyConnectionUnresponsive' should only be called once per connection
4024 mFakePolicy->assertNotifyAnrWasNotCalled();
4025 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004026 mWindow->consumeMotionDown();
4027 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4028 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4029 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004030 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004031 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004032 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004033}
4034
4035/**
4036 * If a window is processing a motion event, and then a key event comes in, the key event should
4037 * not to to the focused window until the motion is processed.
4038 *
4039 * Warning!!!
4040 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4041 * and the injection timeout that we specify when injecting the key.
4042 * We must have the injection timeout (10ms) be smaller than
4043 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4044 *
4045 * If that value changes, this test should also change.
4046 */
4047TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4048 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4050
4051 tapOnWindow();
4052 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4053 ASSERT_TRUE(downSequenceNum);
4054 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4055 ASSERT_TRUE(upSequenceNum);
4056 // Don't finish the events yet, and send a key
4057 // Injection will "succeed" because we will eventually give up and send the key to the focused
4058 // window even if motions are still being processed. But because the injection timeout is short,
4059 // we will receive INJECTION_TIMED_OUT as the result.
4060
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004062 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4064 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004065 // Key will not be sent to the window, yet, because the window is still processing events
4066 // and the key remains pending, waiting for the touch events to be processed
4067 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4068 ASSERT_FALSE(keySequenceNum);
4069
4070 std::this_thread::sleep_for(500ms);
4071 // if we wait long enough though, dispatcher will give up, and still send the key
4072 // to the focused window, even though we have not yet finished the motion event
4073 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4074 mWindow->finishEvent(*downSequenceNum);
4075 mWindow->finishEvent(*upSequenceNum);
4076}
4077
4078/**
4079 * If a window is processing a motion event, and then a key event comes in, the key event should
4080 * not go to the focused window until the motion is processed.
4081 * If then a new motion comes in, then the pending key event should be going to the currently
4082 * focused window right away.
4083 */
4084TEST_F(InputDispatcherSingleWindowAnr,
4085 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4086 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4088
4089 tapOnWindow();
4090 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4091 ASSERT_TRUE(downSequenceNum);
4092 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4093 ASSERT_TRUE(upSequenceNum);
4094 // Don't finish the events yet, and send a key
4095 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004097 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004098 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004099 // At this point, key is still pending, and should not be sent to the application yet.
4100 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4101 ASSERT_FALSE(keySequenceNum);
4102
4103 // Now tap down again. It should cause the pending key to go to the focused window right away.
4104 tapOnWindow();
4105 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4106 // the other events yet. We can finish events in any order.
4107 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4108 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4109 mWindow->consumeMotionDown();
4110 mWindow->consumeMotionUp();
4111 mWindow->assertNoEvents();
4112}
4113
4114class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4115 virtual void SetUp() override {
4116 InputDispatcherTest::SetUp();
4117
Chris Yea209fde2020-07-22 13:54:51 -07004118 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004119 mApplication->setDispatchingTimeout(10ms);
4120 mUnfocusedWindow =
4121 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4122 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4123 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4124 // window.
4125 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004126 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4127 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4128 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004129
4130 mFocusedWindow =
4131 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004132 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004133 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004134 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004135
4136 // Set focused application.
4137 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004138 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004139
4140 // Expect one focus window exist in display.
4141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004142 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004143 mFocusedWindow->consumeFocusEvent(true);
4144 }
4145
4146 virtual void TearDown() override {
4147 InputDispatcherTest::TearDown();
4148
4149 mUnfocusedWindow.clear();
4150 mFocusedWindow.clear();
4151 }
4152
4153protected:
Chris Yea209fde2020-07-22 13:54:51 -07004154 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004155 sp<FakeWindowHandle> mUnfocusedWindow;
4156 sp<FakeWindowHandle> mFocusedWindow;
4157 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4158 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4159 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4160
4161 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4162
4163 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4164
4165private:
4166 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004168 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4169 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004170 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004171 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4172 location));
4173 }
4174};
4175
4176// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4177// should be ANR'd first.
4178TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004179 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004180 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4181 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004182 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004183 mFocusedWindow->consumeMotionDown();
4184 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4185 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4186 // We consumed all events, so no ANR
4187 ASSERT_TRUE(mDispatcher->waitForIdle());
4188 mFakePolicy->assertNotifyAnrWasNotCalled();
4189
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004191 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4192 FOCUSED_WINDOW_LOCATION));
4193 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4194 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004195
4196 const std::chrono::duration timeout =
4197 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004198 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004199 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4200 // sequence to make it consistent
4201 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004202 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004203 mFocusedWindow->consumeMotionDown();
4204 // This cancel is generated because the connection was unresponsive
4205 mFocusedWindow->consumeMotionCancel();
4206 mFocusedWindow->assertNoEvents();
4207 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004208 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004209 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004210 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004211}
4212
4213// If we have 2 windows with identical timeouts that are both unresponsive,
4214// it doesn't matter which order they should have ANR.
4215// But we should receive ANR for both.
4216TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4217 // Set the timeout for unfocused window to match the focused window
4218 mUnfocusedWindow->setDispatchingTimeout(10ms);
4219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4220
4221 tapOnFocusedWindow();
4222 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004223 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4224 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004225
4226 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004227 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4228 mFocusedWindow->getToken() == anrConnectionToken2);
4229 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4230 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004231
4232 ASSERT_TRUE(mDispatcher->waitForIdle());
4233 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004234
4235 mFocusedWindow->consumeMotionDown();
4236 mFocusedWindow->consumeMotionUp();
4237 mUnfocusedWindow->consumeMotionOutside();
4238
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004239 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4240 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004241
4242 // Both applications should be marked as responsive, in any order
4243 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4244 mFocusedWindow->getToken() == responsiveToken2);
4245 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4246 mUnfocusedWindow->getToken() == responsiveToken2);
4247 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004248}
4249
4250// If a window is already not responding, the second tap on the same window should be ignored.
4251// We should also log an error to account for the dropped event (not tested here).
4252// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4253TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4254 tapOnFocusedWindow();
4255 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4256 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4257 // Receive the events, but don't respond
4258 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4259 ASSERT_TRUE(downEventSequenceNum);
4260 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4261 ASSERT_TRUE(upEventSequenceNum);
4262 const std::chrono::duration timeout =
4263 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004264 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004265
4266 // Tap once again
4267 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004268 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4270 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004271 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004272 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4273 FOCUSED_WINDOW_LOCATION));
4274 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4275 // valid touch target
4276 mUnfocusedWindow->assertNoEvents();
4277
4278 // Consume the first tap
4279 mFocusedWindow->finishEvent(*downEventSequenceNum);
4280 mFocusedWindow->finishEvent(*upEventSequenceNum);
4281 ASSERT_TRUE(mDispatcher->waitForIdle());
4282 // The second tap did not go to the focused window
4283 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004284 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004285 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004286 mFakePolicy->assertNotifyAnrWasNotCalled();
4287}
4288
4289// If you tap outside of all windows, there will not be ANR
4290TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004291 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004292 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4293 LOCATION_OUTSIDE_ALL_WINDOWS));
4294 ASSERT_TRUE(mDispatcher->waitForIdle());
4295 mFakePolicy->assertNotifyAnrWasNotCalled();
4296}
4297
4298// Since the focused window is paused, tapping on it should not produce any events
4299TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4300 mFocusedWindow->setPaused(true);
4301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4302
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004303 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004304 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4305 FOCUSED_WINDOW_LOCATION));
4306
4307 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4308 ASSERT_TRUE(mDispatcher->waitForIdle());
4309 // Should not ANR because the window is paused, and touches shouldn't go to it
4310 mFakePolicy->assertNotifyAnrWasNotCalled();
4311
4312 mFocusedWindow->assertNoEvents();
4313 mUnfocusedWindow->assertNoEvents();
4314}
4315
4316/**
4317 * If a window is processing a motion event, and then a key event comes in, the key event should
4318 * not to to the focused window until the motion is processed.
4319 * If a different window becomes focused at this time, the key should go to that window instead.
4320 *
4321 * Warning!!!
4322 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4323 * and the injection timeout that we specify when injecting the key.
4324 * We must have the injection timeout (10ms) be smaller than
4325 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4326 *
4327 * If that value changes, this test should also change.
4328 */
4329TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4330 // Set a long ANR timeout to prevent it from triggering
4331 mFocusedWindow->setDispatchingTimeout(2s);
4332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4333
4334 tapOnUnfocusedWindow();
4335 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4336 ASSERT_TRUE(downSequenceNum);
4337 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4338 ASSERT_TRUE(upSequenceNum);
4339 // Don't finish the events yet, and send a key
4340 // Injection will succeed because we will eventually give up and send the key to the focused
4341 // window even if motions are still being processed.
4342
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004343 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004344 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004345 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004347 // Key will not be sent to the window, yet, because the window is still processing events
4348 // and the key remains pending, waiting for the touch events to be processed
4349 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4350 ASSERT_FALSE(keySequenceNum);
4351
4352 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004353 mFocusedWindow->setFocusable(false);
4354 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004356 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004357
4358 // Focus events should precede the key events
4359 mUnfocusedWindow->consumeFocusEvent(true);
4360 mFocusedWindow->consumeFocusEvent(false);
4361
4362 // Finish the tap events, which should unblock dispatcher
4363 mUnfocusedWindow->finishEvent(*downSequenceNum);
4364 mUnfocusedWindow->finishEvent(*upSequenceNum);
4365
4366 // Now that all queues are cleared and no backlog in the connections, the key event
4367 // can finally go to the newly focused "mUnfocusedWindow".
4368 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4369 mFocusedWindow->assertNoEvents();
4370 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004371 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004372}
4373
4374// When the touch stream is split across 2 windows, and one of them does not respond,
4375// then ANR should be raised and the touch should be canceled for the unresponsive window.
4376// The other window should not be affected by that.
4377TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4378 // Touch Window 1
4379 NotifyMotionArgs motionArgs =
4380 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4381 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4382 mDispatcher->notifyMotion(&motionArgs);
4383 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4384 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4385
4386 // Touch Window 2
4387 int32_t actionPointerDown =
4388 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4389
4390 motionArgs =
4391 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4392 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4393 mDispatcher->notifyMotion(&motionArgs);
4394
4395 const std::chrono::duration timeout =
4396 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004397 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004398
4399 mUnfocusedWindow->consumeMotionDown();
4400 mFocusedWindow->consumeMotionDown();
4401 // Focused window may or may not receive ACTION_MOVE
4402 // But it should definitely receive ACTION_CANCEL due to the ANR
4403 InputEvent* event;
4404 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4405 ASSERT_TRUE(moveOrCancelSequenceNum);
4406 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4407 ASSERT_NE(nullptr, event);
4408 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4409 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4410 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4411 mFocusedWindow->consumeMotionCancel();
4412 } else {
4413 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4414 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004415 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004416 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004417
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004418 mUnfocusedWindow->assertNoEvents();
4419 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004420 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004421}
4422
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004423/**
4424 * If we have no focused window, and a key comes in, we start the ANR timer.
4425 * The focused application should add a focused window before the timer runs out to prevent ANR.
4426 *
4427 * If the user touches another application during this time, the key should be dropped.
4428 * Next, if a new focused window comes in, without toggling the focused application,
4429 * then no ANR should occur.
4430 *
4431 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4432 * but in some cases the policy may not update the focused application.
4433 */
4434TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4435 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4436 std::make_shared<FakeApplicationHandle>();
4437 focusedApplication->setDispatchingTimeout(60ms);
4438 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4439 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4440 mFocusedWindow->setFocusable(false);
4441
4442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4443 mFocusedWindow->consumeFocusEvent(false);
4444
4445 // Send a key. The ANR timer should start because there is no focused window.
4446 // 'focusedApplication' will get blamed if this timer completes.
4447 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004449 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004450 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4451 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004453
4454 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4455 // then the injected touches won't cause the focused event to get dropped.
4456 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4457 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4458 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4459 // For this test, it means that the key would get delivered to the window once it becomes
4460 // focused.
4461 std::this_thread::sleep_for(10ms);
4462
4463 // Touch unfocused window. This should force the pending key to get dropped.
4464 NotifyMotionArgs motionArgs =
4465 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4466 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4467 mDispatcher->notifyMotion(&motionArgs);
4468
4469 // We do not consume the motion right away, because that would require dispatcher to first
4470 // process (== drop) the key event, and by that time, ANR will be raised.
4471 // Set the focused window first.
4472 mFocusedWindow->setFocusable(true);
4473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4474 setFocusedWindow(mFocusedWindow);
4475 mFocusedWindow->consumeFocusEvent(true);
4476 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4477 // to another application. This could be a bug / behaviour in the policy.
4478
4479 mUnfocusedWindow->consumeMotionDown();
4480
4481 ASSERT_TRUE(mDispatcher->waitForIdle());
4482 // Should not ANR because we actually have a focused window. It was just added too slowly.
4483 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4484}
4485
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004486// These tests ensure we cannot send touch events to a window that's positioned behind a window
4487// that has feature NO_INPUT_CHANNEL.
4488// Layout:
4489// Top (closest to user)
4490// mNoInputWindow (above all windows)
4491// mBottomWindow
4492// Bottom (furthest from user)
4493class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4494 virtual void SetUp() override {
4495 InputDispatcherTest::SetUp();
4496
4497 mApplication = std::make_shared<FakeApplicationHandle>();
4498 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4499 "Window without input channel", ADISPLAY_ID_DEFAULT,
4500 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4501
chaviw3277faf2021-05-19 16:45:23 -05004502 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004503 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4504 // It's perfectly valid for this window to not have an associated input channel
4505
4506 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4507 ADISPLAY_ID_DEFAULT);
4508 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4509
4510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4511 }
4512
4513protected:
4514 std::shared_ptr<FakeApplicationHandle> mApplication;
4515 sp<FakeWindowHandle> mNoInputWindow;
4516 sp<FakeWindowHandle> mBottomWindow;
4517};
4518
4519TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4520 PointF touchedPoint = {10, 10};
4521
4522 NotifyMotionArgs motionArgs =
4523 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4524 ADISPLAY_ID_DEFAULT, {touchedPoint});
4525 mDispatcher->notifyMotion(&motionArgs);
4526
4527 mNoInputWindow->assertNoEvents();
4528 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4529 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4530 // and therefore should prevent mBottomWindow from receiving touches
4531 mBottomWindow->assertNoEvents();
4532}
4533
4534/**
4535 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4536 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4537 */
4538TEST_F(InputDispatcherMultiWindowOcclusionTests,
4539 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4540 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4541 "Window with input channel and NO_INPUT_CHANNEL",
4542 ADISPLAY_ID_DEFAULT);
4543
chaviw3277faf2021-05-19 16:45:23 -05004544 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004545 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4547
4548 PointF touchedPoint = {10, 10};
4549
4550 NotifyMotionArgs motionArgs =
4551 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4552 ADISPLAY_ID_DEFAULT, {touchedPoint});
4553 mDispatcher->notifyMotion(&motionArgs);
4554
4555 mNoInputWindow->assertNoEvents();
4556 mBottomWindow->assertNoEvents();
4557}
4558
Vishnu Nair958da932020-08-21 17:12:37 -07004559class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4560protected:
4561 std::shared_ptr<FakeApplicationHandle> mApp;
4562 sp<FakeWindowHandle> mWindow;
4563 sp<FakeWindowHandle> mMirror;
4564
4565 virtual void SetUp() override {
4566 InputDispatcherTest::SetUp();
4567 mApp = std::make_shared<FakeApplicationHandle>();
4568 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4569 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4570 mWindow->getToken());
4571 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4572 mWindow->setFocusable(true);
4573 mMirror->setFocusable(true);
4574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4575 }
4576};
4577
4578TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4579 // Request focus on a mirrored window
4580 setFocusedWindow(mMirror);
4581
4582 // window gets focused
4583 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4585 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004586 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4587}
4588
4589// A focused & mirrored window remains focused only if the window and its mirror are both
4590// focusable.
4591TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4592 setFocusedWindow(mMirror);
4593
4594 // window gets focused
4595 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4597 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004598 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4600 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004601 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4602
4603 mMirror->setFocusable(false);
4604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4605
4606 // window loses focus since one of the windows associated with the token in not focusable
4607 mWindow->consumeFocusEvent(false);
4608
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004609 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4610 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004611 mWindow->assertNoEvents();
4612}
4613
4614// A focused & mirrored window remains focused until the window and its mirror both become
4615// invisible.
4616TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4617 setFocusedWindow(mMirror);
4618
4619 // window gets focused
4620 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4622 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004623 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004624 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4625 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004626 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4627
4628 mMirror->setVisible(false);
4629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4630
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4632 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004633 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4635 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004636 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4637
4638 mWindow->setVisible(false);
4639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4640
4641 // window loses focus only after all windows associated with the token become invisible.
4642 mWindow->consumeFocusEvent(false);
4643
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004644 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4645 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004646 mWindow->assertNoEvents();
4647}
4648
4649// A focused & mirrored window remains focused until both windows are removed.
4650TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4651 setFocusedWindow(mMirror);
4652
4653 // window gets focused
4654 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4656 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004657 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4659 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004660 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4661
4662 // single window is removed but the window token remains focused
4663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4664
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4666 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004667 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4669 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004670 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4671
4672 // Both windows are removed
4673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4674 mWindow->consumeFocusEvent(false);
4675
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004676 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4677 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004678 mWindow->assertNoEvents();
4679}
4680
4681// Focus request can be pending until one window becomes visible.
4682TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4683 // Request focus on an invisible mirror.
4684 mWindow->setVisible(false);
4685 mMirror->setVisible(false);
4686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4687 setFocusedWindow(mMirror);
4688
4689 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004691 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004693
4694 mMirror->setVisible(true);
4695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4696
4697 // window gets focused
4698 mWindow->consumeFocusEvent(true);
4699 // window gets the pending key event
4700 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4701}
Prabir Pradhan99987712020-11-10 18:43:05 -08004702
4703class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4704protected:
4705 std::shared_ptr<FakeApplicationHandle> mApp;
4706 sp<FakeWindowHandle> mWindow;
4707 sp<FakeWindowHandle> mSecondWindow;
4708
4709 void SetUp() override {
4710 InputDispatcherTest::SetUp();
4711 mApp = std::make_shared<FakeApplicationHandle>();
4712 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4713 mWindow->setFocusable(true);
4714 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4715 mSecondWindow->setFocusable(true);
4716
4717 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4719
4720 setFocusedWindow(mWindow);
4721 mWindow->consumeFocusEvent(true);
4722 }
4723
Prabir Pradhanac483a62021-08-06 14:01:18 +00004724 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
4725 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004726 mDispatcher->notifyPointerCaptureChanged(&args);
4727 }
4728
Prabir Pradhanac483a62021-08-06 14:01:18 +00004729 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
4730 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08004731 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhanac483a62021-08-06 14:01:18 +00004732 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
4733 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004734 window->consumeCaptureEvent(enabled);
Prabir Pradhanac483a62021-08-06 14:01:18 +00004735 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08004736 }
4737};
4738
4739TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4740 // Ensure that capture cannot be obtained for unfocused windows.
4741 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4742 mFakePolicy->assertSetPointerCaptureNotCalled();
4743 mSecondWindow->assertNoEvents();
4744
4745 // Ensure that capture can be enabled from the focus window.
4746 requestAndVerifyPointerCapture(mWindow, true);
4747
4748 // Ensure that capture cannot be disabled from a window that does not have capture.
4749 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4750 mFakePolicy->assertSetPointerCaptureNotCalled();
4751
4752 // Ensure that capture can be disabled from the window with capture.
4753 requestAndVerifyPointerCapture(mWindow, false);
4754}
4755
4756TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00004757 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08004758
4759 setFocusedWindow(mSecondWindow);
4760
4761 // Ensure that the capture disabled event was sent first.
4762 mWindow->consumeCaptureEvent(false);
4763 mWindow->consumeFocusEvent(false);
4764 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhanac483a62021-08-06 14:01:18 +00004765 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004766
4767 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhanac483a62021-08-06 14:01:18 +00004768 notifyPointerCaptureChanged({});
4769 notifyPointerCaptureChanged(request);
4770 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08004771 mWindow->assertNoEvents();
4772 mSecondWindow->assertNoEvents();
4773 mFakePolicy->assertSetPointerCaptureNotCalled();
4774}
4775
4776TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhanac483a62021-08-06 14:01:18 +00004777 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08004778
4779 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhanac483a62021-08-06 14:01:18 +00004780 notifyPointerCaptureChanged({});
4781 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004782
4783 // Ensure that Pointer Capture is disabled.
Prabir Pradhanac483a62021-08-06 14:01:18 +00004784 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004785 mWindow->consumeCaptureEvent(false);
4786 mWindow->assertNoEvents();
4787}
4788
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004789TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4790 requestAndVerifyPointerCapture(mWindow, true);
4791
4792 // The first window loses focus.
4793 setFocusedWindow(mSecondWindow);
Prabir Pradhanac483a62021-08-06 14:01:18 +00004794 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004795 mWindow->consumeCaptureEvent(false);
4796
4797 // Request Pointer Capture from the second window before the notification from InputReader
4798 // arrives.
4799 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhanac483a62021-08-06 14:01:18 +00004800 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004801
4802 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhanac483a62021-08-06 14:01:18 +00004803 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004804
4805 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhanac483a62021-08-06 14:01:18 +00004806 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004807
4808 mSecondWindow->consumeFocusEvent(true);
4809 mSecondWindow->consumeCaptureEvent(true);
4810}
4811
Prabir Pradhanac483a62021-08-06 14:01:18 +00004812TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
4813 // App repeatedly enables and disables capture.
4814 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4815 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4816 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
4817 mFakePolicy->assertSetPointerCaptureCalled(false);
4818 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4819 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4820
4821 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
4822 // first request is now stale, this should do nothing.
4823 notifyPointerCaptureChanged(firstRequest);
4824 mWindow->assertNoEvents();
4825
4826 // InputReader notifies that the second request was enabled.
4827 notifyPointerCaptureChanged(secondRequest);
4828 mWindow->consumeCaptureEvent(true);
4829}
4830
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004831class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4832protected:
4833 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004834
4835 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4836 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4837
4838 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4839 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4840
4841 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4842 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4843 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4844 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4845 MAXIMUM_OBSCURING_OPACITY);
4846
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004847 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004848 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004849 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004850
4851 sp<FakeWindowHandle> mTouchWindow;
4852
4853 virtual void SetUp() override {
4854 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004855 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004856 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4857 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4858 }
4859
4860 virtual void TearDown() override {
4861 InputDispatcherTest::TearDown();
4862 mTouchWindow.clear();
4863 }
4864
chaviw3277faf2021-05-19 16:45:23 -05004865 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
4866 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004867 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05004868 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004869 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004870 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004871 return window;
4872 }
4873
4874 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4875 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4876 sp<FakeWindowHandle> window =
4877 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4878 // Generate an arbitrary PID based on the UID
4879 window->setOwnerInfo(1777 + (uid % 10000), uid);
4880 return window;
4881 }
4882
4883 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4884 NotifyMotionArgs args =
4885 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4886 ADISPLAY_ID_DEFAULT, points);
4887 mDispatcher->notifyMotion(&args);
4888 }
4889};
4890
4891TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004892 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004893 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004895
4896 touch();
4897
4898 mTouchWindow->assertNoEvents();
4899}
4900
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004901TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004902 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4903 const sp<FakeWindowHandle>& w =
4904 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4906
4907 touch();
4908
4909 mTouchWindow->assertNoEvents();
4910}
4911
4912TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004913 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4914 const sp<FakeWindowHandle>& w =
4915 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4917
4918 touch();
4919
4920 w->assertNoEvents();
4921}
4922
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004923TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004924 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4925 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004926
4927 touch();
4928
4929 mTouchWindow->consumeAnyMotionDown();
4930}
4931
4932TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004933 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004934 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004935 w->setFrame(Rect(0, 0, 50, 50));
4936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004937
4938 touch({PointF{100, 100}});
4939
4940 mTouchWindow->consumeAnyMotionDown();
4941}
4942
4943TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004944 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004945 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4947
4948 touch();
4949
4950 mTouchWindow->consumeAnyMotionDown();
4951}
4952
4953TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4954 const sp<FakeWindowHandle>& w =
4955 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004957
4958 touch();
4959
4960 mTouchWindow->consumeAnyMotionDown();
4961}
4962
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004963TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4964 const sp<FakeWindowHandle>& w =
4965 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4967
4968 touch();
4969
4970 w->assertNoEvents();
4971}
4972
4973/**
4974 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4975 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4976 * window, the occluding window will still receive ACTION_OUTSIDE event.
4977 */
4978TEST_F(InputDispatcherUntrustedTouchesTest,
4979 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4980 const sp<FakeWindowHandle>& w =
4981 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05004982 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4984
4985 touch();
4986
4987 w->consumeMotionOutside();
4988}
4989
4990TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4991 const sp<FakeWindowHandle>& w =
4992 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05004993 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4995
4996 touch();
4997
4998 InputEvent* event = w->consume();
4999 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5000 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5001 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5002 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5003}
5004
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005005TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005006 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005007 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5008 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5010
5011 touch();
5012
5013 mTouchWindow->consumeAnyMotionDown();
5014}
5015
5016TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5017 const sp<FakeWindowHandle>& w =
5018 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5019 MAXIMUM_OBSCURING_OPACITY);
5020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005021
5022 touch();
5023
5024 mTouchWindow->consumeAnyMotionDown();
5025}
5026
5027TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005028 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005029 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5030 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5032
5033 touch();
5034
5035 mTouchWindow->assertNoEvents();
5036}
5037
5038TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5039 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5040 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005041 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5042 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005043 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005044 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5045 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5047
5048 touch();
5049
5050 mTouchWindow->assertNoEvents();
5051}
5052
5053TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5054 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5055 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005056 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5057 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005058 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005059 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5060 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5062
5063 touch();
5064
5065 mTouchWindow->consumeAnyMotionDown();
5066}
5067
5068TEST_F(InputDispatcherUntrustedTouchesTest,
5069 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5070 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005071 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5072 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005073 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005074 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5075 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005076 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5077
5078 touch();
5079
5080 mTouchWindow->consumeAnyMotionDown();
5081}
5082
5083TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5084 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005085 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5086 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005087 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005088 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5089 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005091
5092 touch();
5093
5094 mTouchWindow->assertNoEvents();
5095}
5096
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005097TEST_F(InputDispatcherUntrustedTouchesTest,
5098 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5099 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005100 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5101 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005102 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005103 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5104 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5106
5107 touch();
5108
5109 mTouchWindow->assertNoEvents();
5110}
5111
5112TEST_F(InputDispatcherUntrustedTouchesTest,
5113 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5114 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005115 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5116 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005117 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005118 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5119 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5121
5122 touch();
5123
5124 mTouchWindow->consumeAnyMotionDown();
5125}
5126
5127TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5128 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005129 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5130 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5132
5133 touch();
5134
5135 mTouchWindow->consumeAnyMotionDown();
5136}
5137
5138TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5139 const sp<FakeWindowHandle>& w =
5140 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5142
5143 touch();
5144
5145 mTouchWindow->consumeAnyMotionDown();
5146}
5147
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005148TEST_F(InputDispatcherUntrustedTouchesTest,
5149 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5150 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5151 const sp<FakeWindowHandle>& w =
5152 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5154
5155 touch();
5156
5157 mTouchWindow->assertNoEvents();
5158}
5159
5160TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5161 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5162 const sp<FakeWindowHandle>& w =
5163 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5165
5166 touch();
5167
5168 mTouchWindow->consumeAnyMotionDown();
5169}
5170
5171TEST_F(InputDispatcherUntrustedTouchesTest,
5172 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5173 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5174 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005175 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5176 OPACITY_ABOVE_THRESHOLD);
5177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5178
5179 touch();
5180
5181 mTouchWindow->consumeAnyMotionDown();
5182}
5183
5184TEST_F(InputDispatcherUntrustedTouchesTest,
5185 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5186 const sp<FakeWindowHandle>& w1 =
5187 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5188 OPACITY_BELOW_THRESHOLD);
5189 const sp<FakeWindowHandle>& w2 =
5190 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5191 OPACITY_BELOW_THRESHOLD);
5192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5193
5194 touch();
5195
5196 mTouchWindow->assertNoEvents();
5197}
5198
5199/**
5200 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5201 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5202 * (which alone would result in allowing touches) does not affect the blocking behavior.
5203 */
5204TEST_F(InputDispatcherUntrustedTouchesTest,
5205 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5206 const sp<FakeWindowHandle>& wB =
5207 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5208 OPACITY_BELOW_THRESHOLD);
5209 const sp<FakeWindowHandle>& wC =
5210 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5211 OPACITY_BELOW_THRESHOLD);
5212 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5213
5214 touch();
5215
5216 mTouchWindow->assertNoEvents();
5217}
5218
5219/**
5220 * This test is testing that a window from a different UID but with same application token doesn't
5221 * block the touch. Apps can share the application token for close UI collaboration for example.
5222 */
5223TEST_F(InputDispatcherUntrustedTouchesTest,
5224 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5225 const sp<FakeWindowHandle>& w =
5226 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5227 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5229
5230 touch();
5231
5232 mTouchWindow->consumeAnyMotionDown();
5233}
5234
arthurhungb89ccb02020-12-30 16:19:01 +08005235class InputDispatcherDragTests : public InputDispatcherTest {
5236protected:
5237 std::shared_ptr<FakeApplicationHandle> mApp;
5238 sp<FakeWindowHandle> mWindow;
5239 sp<FakeWindowHandle> mSecondWindow;
5240 sp<FakeWindowHandle> mDragWindow;
5241
5242 void SetUp() override {
5243 InputDispatcherTest::SetUp();
5244 mApp = std::make_shared<FakeApplicationHandle>();
5245 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5246 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005247 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005248
5249 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5250 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005251 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005252
5253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5254 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5255 }
5256
5257 // Start performing drag, we will create a drag window and transfer touch to it.
5258 void performDrag() {
5259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5260 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5261 {50, 50}))
5262 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5263
5264 // Window should receive motion event.
5265 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5266
5267 // The drag window covers the entire display
5268 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5269 mDispatcher->setInputWindows(
5270 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5271
5272 // Transfer touch focus to the drag window
5273 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5274 true /* isDragDrop */);
5275 mWindow->consumeMotionCancel();
5276 mDragWindow->consumeMotionDown();
5277 }
arthurhung6d4bed92021-03-17 11:59:33 +08005278
5279 // Start performing drag, we will create a drag window and transfer touch to it.
5280 void performStylusDrag() {
5281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5282 injectMotionEvent(mDispatcher,
5283 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5284 AINPUT_SOURCE_STYLUS)
5285 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5286 .pointer(PointerBuilder(0,
5287 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5288 .x(50)
5289 .y(50))
5290 .build()));
5291 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5292
5293 // The drag window covers the entire display
5294 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5295 mDispatcher->setInputWindows(
5296 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5297
5298 // Transfer touch focus to the drag window
5299 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5300 true /* isDragDrop */);
5301 mWindow->consumeMotionCancel();
5302 mDragWindow->consumeMotionDown();
5303 }
arthurhungb89ccb02020-12-30 16:19:01 +08005304};
5305
5306TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5307 performDrag();
5308
5309 // Move on window.
5310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5311 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5312 ADISPLAY_ID_DEFAULT, {50, 50}))
5313 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5314 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5315 mWindow->consumeDragEvent(false, 50, 50);
5316 mSecondWindow->assertNoEvents();
5317
5318 // Move to another window.
5319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5320 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5321 ADISPLAY_ID_DEFAULT, {150, 50}))
5322 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5323 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5324 mWindow->consumeDragEvent(true, 150, 50);
5325 mSecondWindow->consumeDragEvent(false, 50, 50);
5326
5327 // Move back to original window.
5328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5329 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5330 ADISPLAY_ID_DEFAULT, {50, 50}))
5331 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5332 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5333 mWindow->consumeDragEvent(false, 50, 50);
5334 mSecondWindow->consumeDragEvent(true, -50, 50);
5335
5336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5337 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5338 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5339 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5340 mWindow->assertNoEvents();
5341 mSecondWindow->assertNoEvents();
5342}
5343
arthurhungf452d0b2021-01-06 00:19:52 +08005344TEST_F(InputDispatcherDragTests, DragAndDrop) {
5345 performDrag();
5346
5347 // Move on window.
5348 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5349 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5350 ADISPLAY_ID_DEFAULT, {50, 50}))
5351 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5352 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5353 mWindow->consumeDragEvent(false, 50, 50);
5354 mSecondWindow->assertNoEvents();
5355
5356 // Move to another window.
5357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5358 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5359 ADISPLAY_ID_DEFAULT, {150, 50}))
5360 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5361 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5362 mWindow->consumeDragEvent(true, 150, 50);
5363 mSecondWindow->consumeDragEvent(false, 50, 50);
5364
5365 // drop to another window.
5366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5367 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5368 {150, 50}))
5369 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5370 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5371 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5372 mWindow->assertNoEvents();
5373 mSecondWindow->assertNoEvents();
5374}
5375
arthurhung6d4bed92021-03-17 11:59:33 +08005376TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5377 performStylusDrag();
5378
5379 // Move on window and keep button pressed.
5380 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5381 injectMotionEvent(mDispatcher,
5382 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5383 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5384 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5385 .x(50)
5386 .y(50))
5387 .build()))
5388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5389 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5390 mWindow->consumeDragEvent(false, 50, 50);
5391 mSecondWindow->assertNoEvents();
5392
5393 // Move to another window and release button, expect to drop item.
5394 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5395 injectMotionEvent(mDispatcher,
5396 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5397 .buttonState(0)
5398 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5399 .x(150)
5400 .y(50))
5401 .build()))
5402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5403 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5404 mWindow->assertNoEvents();
5405 mSecondWindow->assertNoEvents();
5406 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5407
5408 // nothing to the window.
5409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5410 injectMotionEvent(mDispatcher,
5411 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5412 .buttonState(0)
5413 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5414 .x(150)
5415 .y(50))
5416 .build()))
5417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5418 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5419 mWindow->assertNoEvents();
5420 mSecondWindow->assertNoEvents();
5421}
5422
Arthur Hung6d0571e2021-04-09 20:18:16 +08005423TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5424 performDrag();
5425
5426 // Set second window invisible.
5427 mSecondWindow->setVisible(false);
5428 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5429
5430 // Move on window.
5431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5432 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5433 ADISPLAY_ID_DEFAULT, {50, 50}))
5434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5435 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5436 mWindow->consumeDragEvent(false, 50, 50);
5437 mSecondWindow->assertNoEvents();
5438
5439 // Move to another window.
5440 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5441 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5442 ADISPLAY_ID_DEFAULT, {150, 50}))
5443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5444 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5445 mWindow->consumeDragEvent(true, 150, 50);
5446 mSecondWindow->assertNoEvents();
5447
5448 // drop to another window.
5449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5450 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5451 {150, 50}))
5452 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5453 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5454 mFakePolicy->assertDropTargetEquals(nullptr);
5455 mWindow->assertNoEvents();
5456 mSecondWindow->assertNoEvents();
5457}
5458
Garfield Tane84e6f92019-08-29 17:28:41 -07005459} // namespace android::inputdispatcher