blob: b0914736336ba202fe90a58450bd3df076fcdb95 [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;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080032using android::os::InputEventInjectionResult;
33using android::os::InputEventInjectionSync;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +000034using android::os::TouchOcclusionMode;
Michael Wright44753b12020-07-08 13:48:11 +010035using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080036
Garfield Tane84e6f92019-08-29 17:28:41 -070037namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080038
39// An arbitrary time value.
40static const nsecs_t ARBITRARY_TIME = 1234;
41
42// An arbitrary device id.
43static const int32_t DEVICE_ID = 1;
44
Jeff Brownf086ddb2014-02-11 14:28:48 -080045// An arbitrary display id.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -080046static const int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
Jeff Brownf086ddb2014-02-11 14:28:48 -080047
Michael Wrightd02c5b62014-02-10 15:10:22 -080048// An arbitrary injector pid / uid pair that has permission to inject events.
49static const int32_t INJECTOR_PID = 999;
50static const int32_t INJECTOR_UID = 1001;
51
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000052// An arbitrary pid of the gesture monitor window
53static constexpr int32_t MONITOR_PID = 2001;
54
chaviwd1c23182019-12-20 18:44:56 -080055struct PointF {
56 float x;
57 float y;
58};
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Gang Wang342c9272020-01-13 13:15:04 -050060/**
61 * Return a DOWN key event with KEYCODE_A.
62 */
63static KeyEvent getTestKeyEvent() {
64 KeyEvent event;
65
Garfield Tanfbe732e2020-01-24 11:26:14 -080066 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
67 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
68 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050069 return event;
70}
71
Michael Wrightd02c5b62014-02-10 15:10:22 -080072// --- FakeInputDispatcherPolicy ---
73
74class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
75 InputDispatcherConfiguration mConfig;
76
77protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100078 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080079
80public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100081 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080082
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080083 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080084 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
85 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080086 }
87
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080088 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080089 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
90 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080091 }
92
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070093 void assertFilterInputEventWasNotCalled() {
94 std::scoped_lock lock(mLock);
95 ASSERT_EQ(nullptr, mFilteredEvent);
96 }
Michael Wrightd02c5b62014-02-10 15:10:22 -080097
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -080098 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070099 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800100 ASSERT_TRUE(mConfigurationChangedTime)
101 << "Timed out waiting for configuration changed call";
102 ASSERT_EQ(*mConfigurationChangedTime, when);
103 mConfigurationChangedTime = std::nullopt;
104 }
105
106 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700107 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800108 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800109 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800110 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
111 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
112 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
113 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
114 mLastNotifySwitch = std::nullopt;
115 }
116
chaviwfd6d3512019-03-25 13:23:49 -0700117 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700118 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800119 ASSERT_EQ(touchedToken, mOnPointerDownToken);
120 mOnPointerDownToken.clear();
121 }
122
123 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700124 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800125 ASSERT_TRUE(mOnPointerDownToken == nullptr)
126 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700127 }
128
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700129 // This function must be called soon after the expected ANR timer starts,
130 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500131 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700132 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500133 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
134 std::shared_ptr<InputApplicationHandle> application;
135 { // acquire lock
136 std::unique_lock lock(mLock);
137 android::base::ScopedLockAssertion assumeLocked(mLock);
138 ASSERT_NO_FATAL_FAILURE(
139 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
140 } // release lock
141 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700142 }
143
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000144 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
145 const sp<IBinder>& expectedConnectionToken) {
146 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500147 ASSERT_EQ(expectedConnectionToken, connectionToken);
148 }
149
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000150 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
151 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500152 ASSERT_EQ(expectedConnectionToken, connectionToken);
153 }
154
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000155 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
156 int32_t pid = getUnresponsiveMonitorPid(timeout);
157 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500158 }
159
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000160 void assertNotifyMonitorResponsiveWasCalled() {
161 int32_t pid = getResponsiveMonitorPid();
162 ASSERT_EQ(MONITOR_PID, pid);
163 }
164
165 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500166 std::unique_lock lock(mLock);
167 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000168 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
169 }
170
171 sp<IBinder> getResponsiveWindowToken() {
172 std::unique_lock lock(mLock);
173 android::base::ScopedLockAssertion assumeLocked(mLock);
174 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
175 }
176
177 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
178 std::unique_lock lock(mLock);
179 android::base::ScopedLockAssertion assumeLocked(mLock);
180 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
181 }
182
183 int32_t getResponsiveMonitorPid() {
184 std::unique_lock lock(mLock);
185 android::base::ScopedLockAssertion assumeLocked(mLock);
186 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
189 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
190 // for a specific container to become non-empty. When the container is non-empty, return the
191 // first entry from the container and erase it.
192 template <class T>
193 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
194 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
195 const std::chrono::time_point start = std::chrono::steady_clock::now();
196 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700197
198 // If there is an ANR, Dispatcher won't be idle because there are still events
199 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
200 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500201 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
202 // to provide it some time to act. 100ms seems reasonable.
203 mNotifyAnr.wait_for(lock, timeToWait,
204 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700205 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500206 if (storage.empty()) {
207 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700209 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700210 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
211 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700212 if (std::chrono::abs(timeout - waited) > 100ms) {
213 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
214 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
215 << "ms, but waited "
216 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
217 << "ms instead";
218 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500219 T token = storage.front();
220 storage.pop();
221 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700222 }
223
224 void assertNotifyAnrWasNotCalled() {
225 std::scoped_lock lock(mLock);
226 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000227 ASSERT_TRUE(mAnrWindowTokens.empty());
228 ASSERT_TRUE(mAnrMonitorPids.empty());
229 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500230 << "ANR was not called, but please also consume the 'connection is responsive' "
231 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000232 ASSERT_TRUE(mResponsiveMonitorPids.empty())
233 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
234 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700235 }
236
Garfield Tan1c7bc862020-01-28 13:24:04 -0800237 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
238 mConfig.keyRepeatTimeout = timeout;
239 mConfig.keyRepeatDelay = delay;
240 }
241
Prabir Pradhan99987712020-11-10 18:43:05 -0800242 void waitForSetPointerCapture(bool enabled) {
243 std::unique_lock lock(mLock);
244 base::ScopedLockAssertion assumeLocked(mLock);
245
246 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
247 [this, enabled]() REQUIRES(mLock) {
248 return mPointerCaptureEnabled &&
249 *mPointerCaptureEnabled ==
250 enabled;
251 })) {
252 FAIL() << "Timed out waiting for setPointerCapture(" << enabled << ") to be called.";
253 }
254 mPointerCaptureEnabled.reset();
255 }
256
257 void assertSetPointerCaptureNotCalled() {
258 std::unique_lock lock(mLock);
259 base::ScopedLockAssertion assumeLocked(mLock);
260
261 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
262 FAIL() << "Expected setPointerCapture(enabled) to not be called, but was called. "
263 "enabled = "
264 << *mPointerCaptureEnabled;
265 }
266 mPointerCaptureEnabled.reset();
267 }
268
arthurhungf452d0b2021-01-06 00:19:52 +0800269 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
270 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800271 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800272 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800273 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800274 }
275
Michael Wrightd02c5b62014-02-10 15:10:22 -0800276private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700277 std::mutex mLock;
278 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
279 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
280 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
281 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800282
Prabir Pradhan99987712020-11-10 18:43:05 -0800283 std::condition_variable mPointerCaptureChangedCondition;
284 std::optional<bool> mPointerCaptureEnabled GUARDED_BY(mLock);
285
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700286 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700287 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000288 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
289 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
290 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
291 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700292 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700293
arthurhungf452d0b2021-01-06 00:19:52 +0800294 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800295 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800296
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600297 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700298 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800299 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300 }
301
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000302 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700303 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000304 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700305 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500306 }
307
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000308 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500309 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000310 mAnrMonitorPids.push(pid);
311 mNotifyAnr.notify_all();
312 }
313
314 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
315 std::scoped_lock lock(mLock);
316 mResponsiveWindowTokens.push(connectionToken);
317 mNotifyAnr.notify_all();
318 }
319
320 void notifyMonitorResponsive(int32_t pid) override {
321 std::scoped_lock lock(mLock);
322 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500323 mNotifyAnr.notify_all();
324 }
325
326 void notifyNoFocusedWindowAnr(
327 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
328 std::scoped_lock lock(mLock);
329 mAnrApplications.push(applicationHandle);
330 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800331 }
332
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600333 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600335 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700336
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600337 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700338 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
339 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
340 const std::vector<float>& values) override {}
341
342 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
343 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000344
Chris Yefb552902021-02-03 17:18:37 -0800345 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
346
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600347 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800348 *outConfig = mConfig;
349 }
350
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600351 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700352 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800353 switch (inputEvent->getType()) {
354 case AINPUT_EVENT_TYPE_KEY: {
355 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800356 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800357 break;
358 }
359
360 case AINPUT_EVENT_TYPE_MOTION: {
361 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800362 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800363 break;
364 }
365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366 return true;
367 }
368
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600369 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600371 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800372
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600373 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800374 return 0;
375 }
376
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600377 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 return false;
379 }
380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
382 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700383 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800384 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
385 * essentially a passthrough for notifySwitch.
386 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800387 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 }
389
Sean Stoutb4e0a592021-02-23 07:34:53 -0800390 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800392 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
393 return pid == INJECTOR_PID && uid == INJECTOR_UID;
394 }
Jackal Guof9696682018-10-05 12:23:23 +0800395
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600396 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700397 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700398 mOnPointerDownToken = newToken;
399 }
400
Prabir Pradhan99987712020-11-10 18:43:05 -0800401 void setPointerCapture(bool enabled) override {
402 std::scoped_lock lock(mLock);
403 mPointerCaptureEnabled = {enabled};
404 mPointerCaptureChangedCondition.notify_all();
405 }
406
arthurhungf452d0b2021-01-06 00:19:52 +0800407 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
408 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800409 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800410 mDropTargetWindowToken = token;
411 }
412
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800413 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
414 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700415 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800416 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
417 ASSERT_EQ(mFilteredEvent->getType(), type);
418
419 if (type == AINPUT_EVENT_TYPE_KEY) {
420 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
421 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
422 EXPECT_EQ(keyEvent.getAction(), action);
423 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
424 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
425 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
426 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
427 EXPECT_EQ(motionEvent.getAction(), action);
428 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
429 } else {
430 FAIL() << "Unknown type: " << type;
431 }
432
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800433 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435};
436
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437// --- InputDispatcherTest ---
438
439class InputDispatcherTest : public testing::Test {
440protected:
441 sp<FakeInputDispatcherPolicy> mFakePolicy;
442 sp<InputDispatcher> mDispatcher;
443
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000444 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 mFakePolicy = new FakeInputDispatcherPolicy();
446 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800447 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000448 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700449 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450 }
451
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000452 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700453 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 mFakePolicy.clear();
455 mDispatcher.clear();
456 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700457
458 /**
459 * Used for debugging when writing the test
460 */
461 void dumpDispatcherState() {
462 std::string dump;
463 mDispatcher->dump(dump);
464 std::stringstream ss(dump);
465 std::string to;
466
467 while (std::getline(ss, to, '\n')) {
468 ALOGE("%s", to.c_str());
469 }
470 }
Vishnu Nair958da932020-08-21 17:12:37 -0700471
472 void setFocusedWindow(const sp<InputWindowHandle>& window,
473 const sp<InputWindowHandle>& focusedWindow = nullptr) {
474 FocusRequest request;
475 request.token = window->getToken();
476 if (focusedWindow) {
477 request.focusedToken = focusedWindow->getToken();
478 }
479 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
480 request.displayId = window->getInfo()->displayId;
481 mDispatcher->setFocusedWindow(request);
482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483};
484
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
486 KeyEvent event;
487
488 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800489 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
490 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600491 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
492 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800493 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700494 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800495 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 << "Should reject key events with undefined action.";
497
498 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800499 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
500 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600501 ARBITRARY_TIME, 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 ACTION_MULTIPLE.";
506}
507
508TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
509 MotionEvent event;
510 PointerProperties pointerProperties[MAX_POINTERS + 1];
511 PointerCoords pointerCoords[MAX_POINTERS + 1];
512 for (int i = 0; i <= MAX_POINTERS; i++) {
513 pointerProperties[i].clear();
514 pointerProperties[i].id = i;
515 pointerCoords[i].clear();
516 }
517
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800518 // Some constants commonly used below
519 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
520 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
521 constexpr int32_t metaState = AMETA_NONE;
522 constexpr MotionClassification classification = MotionClassification::NONE;
523
chaviw9eaa22c2020-07-01 16:21:27 -0700524 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800526 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700527 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
528 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700529 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
530 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700531 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800532 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700533 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800534 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 << "Should reject motion events with undefined action.";
536
537 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800538 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700539 AMOTION_EVENT_ACTION_POINTER_DOWN |
540 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700541 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
542 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700543 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700544 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
545 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800546 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700547 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800548 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549 << "Should reject motion events with pointer down index too large.";
550
Garfield Tanfbe732e2020-01-24 11:26:14 -0800551 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700552 AMOTION_EVENT_ACTION_POINTER_DOWN |
553 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700554 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
555 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700556 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700557 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
558 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800559 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700560 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 << "Should reject motion events with pointer down index too small.";
563
564 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800565 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700566 AMOTION_EVENT_ACTION_POINTER_UP |
567 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700568 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
569 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700570 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700571 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
572 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800573 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700574 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800575 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 << "Should reject motion events with pointer up index too large.";
577
Garfield Tanfbe732e2020-01-24 11:26:14 -0800578 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700579 AMOTION_EVENT_ACTION_POINTER_UP |
580 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700581 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
582 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700583 AMOTION_EVENT_INVALID_DISPLAY_SIZE, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
chaviw9eaa22c2020-07-01 16:21:27 -0700584 ARBITRARY_TIME, ARBITRARY_TIME, /*pointerCount*/ 1, pointerProperties,
585 pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800586 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700587 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800588 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800589 << "Should reject motion events with pointer up index too small.";
590
591 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
593 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700594 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700595 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
596 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700597 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800598 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700599 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800600 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 << "Should reject motion events with 0 pointers.";
602
Garfield Tanfbe732e2020-01-24 11:26:14 -0800603 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
604 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700605 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700606 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
607 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700608 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700610 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612 << "Should reject motion events with more than MAX_POINTERS pointers.";
613
614 // Rejects motion events with invalid pointer ids.
615 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
617 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700618 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700619 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
620 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with pointer ids less than 0.";
626
627 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800628 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
629 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700630 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700631 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
632 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700633 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700635 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
638
639 // Rejects motion events with duplicate pointer ids.
640 pointerProperties[0].id = 1;
641 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800642 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
643 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700644 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky84f07f02021-04-16 10:42:42 -0700645 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_DISPLAY_SIZE,
646 AMOTION_EVENT_INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700647 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800648 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700649 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800650 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 << "Should reject motion events with duplicate pointer ids.";
652}
653
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800654/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
655
656TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
657 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800658 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800659 mDispatcher->notifyConfigurationChanged(&args);
660 ASSERT_TRUE(mDispatcher->waitForIdle());
661
662 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
663}
664
665TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800666 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
667 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800668 mDispatcher->notifySwitch(&args);
669
670 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
671 args.policyFlags |= POLICY_FLAG_TRUSTED;
672 mFakePolicy->assertNotifySwitchWasCalled(args);
673}
674
Arthur Hungb92218b2018-08-14 12:00:21 +0800675// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700676static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700677static constexpr std::chrono::nanoseconds DISPATCHING_TIMEOUT = 5s;
Arthur Hungb92218b2018-08-14 12:00:21 +0800678
679class FakeApplicationHandle : public InputApplicationHandle {
680public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700681 FakeApplicationHandle() {
682 mInfo.name = "Fake Application";
683 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500684 mInfo.dispatchingTimeoutMillis =
685 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700686 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800687 virtual ~FakeApplicationHandle() {}
688
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000689 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700690
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500691 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
692 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700693 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800694};
695
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800696class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800697public:
Garfield Tan15601662020-09-22 15:32:38 -0700698 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800699 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700700 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800701 }
702
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800703 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700704 InputEvent* event;
705 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
706 if (!consumeSeq) {
707 return nullptr;
708 }
709 finishEvent(*consumeSeq);
710 return event;
711 }
712
713 /**
714 * Receive an event without acknowledging it.
715 * Return the sequence number that could later be used to send finished signal.
716 */
717 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800718 uint32_t consumeSeq;
719 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800720
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800721 std::chrono::time_point start = std::chrono::steady_clock::now();
722 status_t status = WOULD_BLOCK;
723 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800724 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800725 &event);
726 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
727 if (elapsed > 100ms) {
728 break;
729 }
730 }
731
732 if (status == WOULD_BLOCK) {
733 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700734 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800735 }
736
737 if (status != OK) {
738 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700739 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800740 }
741 if (event == nullptr) {
742 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700743 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800744 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700745 if (outEvent != nullptr) {
746 *outEvent = event;
747 }
748 return consumeSeq;
749 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800750
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 /**
752 * To be used together with "receiveEvent" to complete the consumption of an event.
753 */
754 void finishEvent(uint32_t consumeSeq) {
755 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
756 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800757 }
758
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000759 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
760 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
761 ASSERT_EQ(OK, status);
762 }
763
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000764 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
765 std::optional<int32_t> expectedDisplayId,
766 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767 InputEvent* event = consume();
768
769 ASSERT_NE(nullptr, event) << mName.c_str()
770 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800771 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700772 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800773 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800774
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000775 if (expectedDisplayId.has_value()) {
776 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
777 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800778
Tiger Huang8664f8c2018-10-11 19:14:35 +0800779 switch (expectedEventType) {
780 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800781 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
782 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000783 if (expectedFlags.has_value()) {
784 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
785 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800786 break;
787 }
788 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800789 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
790 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000791 if (expectedFlags.has_value()) {
792 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
793 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800794 break;
795 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100796 case AINPUT_EVENT_TYPE_FOCUS: {
797 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
798 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800799 case AINPUT_EVENT_TYPE_CAPTURE: {
800 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
801 }
arthurhungb89ccb02020-12-30 16:19:01 +0800802 case AINPUT_EVENT_TYPE_DRAG: {
803 FAIL() << "Use 'consumeDragEvent' for DRAG events";
804 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800805 default: {
806 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
807 }
808 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800809 }
810
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100811 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
812 InputEvent* event = consume();
813 ASSERT_NE(nullptr, event) << mName.c_str()
814 << ": consumer should have returned non-NULL event.";
815 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
816 << "Got " << inputEventTypeToString(event->getType())
817 << " event instead of FOCUS event";
818
819 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
820 << mName.c_str() << ": event displayId should always be NONE.";
821
822 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
823 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
824 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
825 }
826
Prabir Pradhan99987712020-11-10 18:43:05 -0800827 void consumeCaptureEvent(bool hasCapture) {
828 const InputEvent* event = consume();
829 ASSERT_NE(nullptr, event) << mName.c_str()
830 << ": consumer should have returned non-NULL event.";
831 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
832 << "Got " << inputEventTypeToString(event->getType())
833 << " event instead of CAPTURE event";
834
835 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
836 << mName.c_str() << ": event displayId should always be NONE.";
837
838 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
839 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
840 }
841
arthurhungb89ccb02020-12-30 16:19:01 +0800842 void consumeDragEvent(bool isExiting, float x, float y) {
843 const InputEvent* event = consume();
844 ASSERT_NE(nullptr, event) << mName.c_str()
845 << ": consumer should have returned non-NULL event.";
846 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
847 << "Got " << inputEventTypeToString(event->getType())
848 << " event instead of DRAG event";
849
850 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
851 << mName.c_str() << ": event displayId should always be NONE.";
852
853 const auto& dragEvent = static_cast<const DragEvent&>(*event);
854 EXPECT_EQ(isExiting, dragEvent.isExiting());
855 EXPECT_EQ(x, dragEvent.getX());
856 EXPECT_EQ(y, dragEvent.getY());
857 }
858
chaviwd1c23182019-12-20 18:44:56 -0800859 void assertNoEvents() {
860 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700861 if (event == nullptr) {
862 return;
863 }
864 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
865 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
866 ADD_FAILURE() << "Received key event "
867 << KeyEvent::actionToString(keyEvent.getAction());
868 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
869 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
870 ADD_FAILURE() << "Received motion event "
871 << MotionEvent::actionToString(motionEvent.getAction());
872 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
873 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
874 ADD_FAILURE() << "Received focus event, hasFocus = "
875 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800876 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
877 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
878 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
879 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700880 }
881 FAIL() << mName.c_str()
882 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800883 }
884
885 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
886
887protected:
888 std::unique_ptr<InputConsumer> mConsumer;
889 PreallocatedInputEventFactory mEventFactory;
890
891 std::string mName;
892};
893
894class FakeWindowHandle : public InputWindowHandle {
895public:
896 static const int32_t WIDTH = 600;
897 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800898
Chris Yea209fde2020-07-22 13:54:51 -0700899 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800900 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500901 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800902 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500903 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700904 base::Result<std::unique_ptr<InputChannel>> channel =
905 dispatcher->createInputChannel(name);
906 token = (*channel)->getConnectionToken();
907 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800908 }
909
910 inputApplicationHandle->updateInfo();
911 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
912
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500913 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700914 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800915 mInfo.name = name;
Michael Wright44753b12020-07-08 13:48:11 +0100916 mInfo.type = InputWindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500917 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000918 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800919 mInfo.frameLeft = 0;
920 mInfo.frameTop = 0;
921 mInfo.frameRight = WIDTH;
922 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700923 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800924 mInfo.globalScaleFactor = 1.0;
925 mInfo.touchableRegion.clear();
926 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
927 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700928 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800929 mInfo.hasWallpaper = false;
930 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800931 mInfo.ownerPid = INJECTOR_PID;
932 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800933 mInfo.displayId = displayId;
934 }
935
936 virtual bool updateInfo() { return true; }
937
Vishnu Nair47074b82020-08-14 11:54:47 -0700938 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800939
Vishnu Nair958da932020-08-21 17:12:37 -0700940 void setVisible(bool visible) { mInfo.visible = visible; }
941
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700942 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500943 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700944 }
945
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 void setPaused(bool paused) { mInfo.paused = paused; }
947
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000948 void setAlpha(float alpha) { mInfo.alpha = alpha; }
949
950 void setTouchOcclusionMode(android::os::TouchOcclusionMode mode) {
951 mInfo.touchOcclusionMode = mode;
952 }
953
Bernardo Rufino7393d172021-02-26 13:56:11 +0000954 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
955
chaviwd1c23182019-12-20 18:44:56 -0800956 void setFrame(const Rect& frame) {
957 mInfo.frameLeft = frame.left;
958 mInfo.frameTop = frame.top;
959 mInfo.frameRight = frame.right;
960 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800961 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800962 mInfo.touchableRegion.clear();
963 mInfo.addTouchableRegion(frame);
964 }
965
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000966 void addFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags |= flags; }
967
Michael Wright44753b12020-07-08 13:48:11 +0100968 void setFlags(Flags<InputWindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800969
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500970 void setInputFeatures(InputWindowInfo::Feature features) { mInfo.inputFeatures = features; }
971
chaviw9eaa22c2020-07-01 16:21:27 -0700972 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
973 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
974 }
975
976 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700977
yunho.shinf4a80b82020-11-16 21:13:57 +0900978 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
979
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800980 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
981 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
982 expectedFlags);
983 }
984
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700985 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
986 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
987 }
988
Svet Ganov5d3bc372020-01-26 23:11:07 -0800989 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000990 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800991 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
992 expectedFlags);
993 }
994
995 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000996 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -0800997 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
998 expectedFlags);
999 }
1000
1001 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001002 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001003 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1004 }
1005
1006 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1007 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001008 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1009 expectedFlags);
1010 }
1011
Svet Ganov5d3bc372020-01-26 23:11:07 -08001012 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001013 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1014 int32_t expectedFlags = 0) {
1015 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1016 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001017 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1018 }
1019
1020 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001021 int32_t expectedFlags = 0) {
1022 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1023 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001024 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1025 }
1026
1027 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001028 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001029 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1030 expectedFlags);
1031 }
1032
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001033 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1034 int32_t expectedFlags = 0) {
1035 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1036 expectedFlags);
1037 }
1038
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001039 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1040 ASSERT_NE(mInputReceiver, nullptr)
1041 << "Cannot consume events from a window with no receiver";
1042 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1043 }
1044
Prabir Pradhan99987712020-11-10 18:43:05 -08001045 void consumeCaptureEvent(bool hasCapture) {
1046 ASSERT_NE(mInputReceiver, nullptr)
1047 << "Cannot consume events from a window with no receiver";
1048 mInputReceiver->consumeCaptureEvent(hasCapture);
1049 }
1050
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001051 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1052 std::optional<int32_t> expectedDisplayId,
1053 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001054 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1055 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1056 expectedFlags);
1057 }
1058
arthurhungb89ccb02020-12-30 16:19:01 +08001059 void consumeDragEvent(bool isExiting, float x, float y) {
1060 mInputReceiver->consumeDragEvent(isExiting, x, y);
1061 }
1062
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001063 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001064 if (mInputReceiver == nullptr) {
1065 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1066 return std::nullopt;
1067 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001068 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001069 }
1070
1071 void finishEvent(uint32_t sequenceNum) {
1072 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1073 mInputReceiver->finishEvent(sequenceNum);
1074 }
1075
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001076 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1077 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1078 mInputReceiver->sendTimeline(inputEventId, timeline);
1079 }
1080
chaviwaf87b3e2019-10-01 16:59:28 -07001081 InputEvent* consume() {
1082 if (mInputReceiver == nullptr) {
1083 return nullptr;
1084 }
1085 return mInputReceiver->consume();
1086 }
1087
Arthur Hungb92218b2018-08-14 12:00:21 +08001088 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001089 if (mInputReceiver == nullptr &&
1090 mInfo.inputFeatures.test(InputWindowInfo::Feature::NO_INPUT_CHANNEL)) {
1091 return; // Can't receive events if the window does not have input channel
1092 }
1093 ASSERT_NE(nullptr, mInputReceiver)
1094 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001095 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001096 }
1097
chaviwaf87b3e2019-10-01 16:59:28 -07001098 sp<IBinder> getToken() { return mInfo.token; }
1099
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001100 const std::string& getName() { return mName; }
1101
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001102 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1103 mInfo.ownerPid = ownerPid;
1104 mInfo.ownerUid = ownerUid;
1105 }
1106
chaviwd1c23182019-12-20 18:44:56 -08001107private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001108 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001109 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001110 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001111};
1112
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001113std::atomic<int32_t> FakeWindowHandle::sId{1};
1114
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001115static InputEventInjectionResult injectKey(
1116 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1117 int32_t displayId = ADISPLAY_ID_NONE,
1118 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001119 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1120 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001121 KeyEvent event;
1122 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1123
1124 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001125 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001126 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1127 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001128
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001129 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1130 if (!allowKeyRepeat) {
1131 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1132 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001133 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001134 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001135 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001136}
1137
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001138static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1139 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001140 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1141}
1142
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001143// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1144// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1145// has to be woken up to process the repeating key.
1146static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1147 int32_t displayId = ADISPLAY_ID_NONE) {
1148 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1149 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1150 /* allowKeyRepeat */ false);
1151}
1152
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001153static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1154 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001155 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1156}
1157
Garfield Tandf26e862020-07-01 20:18:19 -07001158class PointerBuilder {
1159public:
1160 PointerBuilder(int32_t id, int32_t toolType) {
1161 mProperties.clear();
1162 mProperties.id = id;
1163 mProperties.toolType = toolType;
1164 mCoords.clear();
1165 }
1166
1167 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1168
1169 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1170
1171 PointerBuilder& axis(int32_t axis, float value) {
1172 mCoords.setAxisValue(axis, value);
1173 return *this;
1174 }
1175
1176 PointerProperties buildProperties() const { return mProperties; }
1177
1178 PointerCoords buildCoords() const { return mCoords; }
1179
1180private:
1181 PointerProperties mProperties;
1182 PointerCoords mCoords;
1183};
1184
1185class MotionEventBuilder {
1186public:
1187 MotionEventBuilder(int32_t action, int32_t source) {
1188 mAction = action;
1189 mSource = source;
1190 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1191 }
1192
1193 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1194 mEventTime = eventTime;
1195 return *this;
1196 }
1197
1198 MotionEventBuilder& displayId(int32_t displayId) {
1199 mDisplayId = displayId;
1200 return *this;
1201 }
1202
1203 MotionEventBuilder& actionButton(int32_t actionButton) {
1204 mActionButton = actionButton;
1205 return *this;
1206 }
1207
arthurhung6d4bed92021-03-17 11:59:33 +08001208 MotionEventBuilder& buttonState(int32_t buttonState) {
1209 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001210 return *this;
1211 }
1212
1213 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1214 mRawXCursorPosition = rawXCursorPosition;
1215 return *this;
1216 }
1217
1218 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1219 mRawYCursorPosition = rawYCursorPosition;
1220 return *this;
1221 }
1222
1223 MotionEventBuilder& pointer(PointerBuilder pointer) {
1224 mPointers.push_back(pointer);
1225 return *this;
1226 }
1227
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001228 MotionEventBuilder& addFlag(uint32_t flags) {
1229 mFlags |= flags;
1230 return *this;
1231 }
1232
Garfield Tandf26e862020-07-01 20:18:19 -07001233 MotionEvent build() {
1234 std::vector<PointerProperties> pointerProperties;
1235 std::vector<PointerCoords> pointerCoords;
1236 for (const PointerBuilder& pointer : mPointers) {
1237 pointerProperties.push_back(pointer.buildProperties());
1238 pointerCoords.push_back(pointer.buildCoords());
1239 }
1240
1241 // Set mouse cursor position for the most common cases to avoid boilerplate.
1242 if (mSource == AINPUT_SOURCE_MOUSE &&
1243 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1244 mPointers.size() == 1) {
1245 mRawXCursorPosition = pointerCoords[0].getX();
1246 mRawYCursorPosition = pointerCoords[0].getY();
1247 }
1248
1249 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001250 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001251 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001252 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001253 mButtonState, MotionClassification::NONE, identityTransform,
1254 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Evan Rosky84f07f02021-04-16 10:42:42 -07001255 mRawYCursorPosition, mDisplayWidth, mDisplayHeight, mEventTime, mEventTime,
1256 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001257
1258 return event;
1259 }
1260
1261private:
1262 int32_t mAction;
1263 int32_t mSource;
1264 nsecs_t mEventTime;
1265 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1266 int32_t mActionButton{0};
1267 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001268 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001269 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1270 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
Evan Rosky84f07f02021-04-16 10:42:42 -07001271 int32_t mDisplayWidth{AMOTION_EVENT_INVALID_DISPLAY_SIZE};
1272 int32_t mDisplayHeight{AMOTION_EVENT_INVALID_DISPLAY_SIZE};
Garfield Tandf26e862020-07-01 20:18:19 -07001273
1274 std::vector<PointerBuilder> mPointers;
1275};
1276
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001277static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001278 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1279 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001280 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001281 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1282 injectionTimeout,
1283 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1284}
1285
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001286static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001287 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1288 const PointF& position,
1289 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001290 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1291 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001293 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001294 MotionEvent event = MotionEventBuilder(action, source)
1295 .displayId(displayId)
1296 .eventTime(eventTime)
1297 .rawXCursorPosition(cursorPosition.x)
1298 .rawYCursorPosition(cursorPosition.y)
1299 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1300 .x(position.x)
1301 .y(position.y))
1302 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001303
1304 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001305 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001306}
1307
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001308static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1309 int32_t source, int32_t displayId,
1310 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001311 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001312}
1313
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001314static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1315 int32_t source, int32_t displayId,
1316 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001317 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001318}
1319
Jackal Guof9696682018-10-05 12:23:23 +08001320static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1321 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1322 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001323 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1324 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1325 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001326
1327 return args;
1328}
1329
chaviwd1c23182019-12-20 18:44:56 -08001330static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1331 const std::vector<PointF>& points) {
1332 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001333 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1334 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1335 }
1336
chaviwd1c23182019-12-20 18:44:56 -08001337 PointerProperties pointerProperties[pointerCount];
1338 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001339
chaviwd1c23182019-12-20 18:44:56 -08001340 for (size_t i = 0; i < pointerCount; i++) {
1341 pointerProperties[i].clear();
1342 pointerProperties[i].id = i;
1343 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001344
chaviwd1c23182019-12-20 18:44:56 -08001345 pointerCoords[i].clear();
1346 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1347 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1348 }
Jackal Guof9696682018-10-05 12:23:23 +08001349
1350 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1351 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001352 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001353 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1354 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001355 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1356 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001357 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1358 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001359
1360 return args;
1361}
1362
chaviwd1c23182019-12-20 18:44:56 -08001363static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1364 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1365}
1366
Prabir Pradhan99987712020-11-10 18:43:05 -08001367static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(bool enabled) {
1368 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), enabled);
1369}
1370
Arthur Hungb92218b2018-08-14 12:00:21 +08001371TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001372 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001373 sp<FakeWindowHandle> window =
1374 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001375
Arthur Hung72d8dc32020-03-28 00:48:39 +00001376 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1378 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1379 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001380
1381 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001382 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001383}
1384
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001385/**
1386 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1387 * To ensure that window receives only events that were directly inside of it, add
1388 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1389 * when finding touched windows.
1390 * This test serves as a sanity check for the next test, where setInputWindows is
1391 * called twice.
1392 */
1393TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001394 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001395 sp<FakeWindowHandle> window =
1396 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1397 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001398 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001399
1400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001402 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1403 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001405
1406 // Window should receive motion event.
1407 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1408}
1409
1410/**
1411 * Calling setInputWindows twice, with the same info, should not cause any issues.
1412 * To ensure that window receives only events that were directly inside of it, add
1413 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1414 * when finding touched windows.
1415 */
1416TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001417 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001418 sp<FakeWindowHandle> window =
1419 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1420 window->setFrame(Rect(0, 0, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01001421 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001422
1423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001426 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1427 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001429
1430 // Window should receive motion event.
1431 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1432}
1433
Arthur Hungb92218b2018-08-14 12:00:21 +08001434// The foreground window should receive the first touch down event.
1435TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001436 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001437 sp<FakeWindowHandle> windowTop =
1438 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1439 sp<FakeWindowHandle> windowSecond =
1440 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001441
Arthur Hung72d8dc32020-03-28 00:48:39 +00001442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1444 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001446
1447 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001448 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001449 windowSecond->assertNoEvents();
1450}
1451
Garfield Tandf26e862020-07-01 20:18:19 -07001452TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001453 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001454 sp<FakeWindowHandle> windowLeft =
1455 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1456 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001457 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001458 sp<FakeWindowHandle> windowRight =
1459 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1460 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001461 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001462
1463 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1464
1465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1466
1467 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001469 injectMotionEvent(mDispatcher,
1470 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1471 AINPUT_SOURCE_MOUSE)
1472 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1473 .x(900)
1474 .y(400))
1475 .build()));
1476 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1477 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1478 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1479 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1480
1481 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001483 injectMotionEvent(mDispatcher,
1484 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1485 AINPUT_SOURCE_MOUSE)
1486 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1487 .x(300)
1488 .y(400))
1489 .build()));
1490 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1491 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1492 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1493 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1494 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1495 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1496
1497 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001499 injectMotionEvent(mDispatcher,
1500 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1501 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1502 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1503 .x(300)
1504 .y(400))
1505 .build()));
1506 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1507
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001508 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001509 injectMotionEvent(mDispatcher,
1510 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1511 AINPUT_SOURCE_MOUSE)
1512 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1513 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1514 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1515 .x(300)
1516 .y(400))
1517 .build()));
1518 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1519 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1520
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001522 injectMotionEvent(mDispatcher,
1523 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1524 AINPUT_SOURCE_MOUSE)
1525 .buttonState(0)
1526 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1527 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1528 .x(300)
1529 .y(400))
1530 .build()));
1531 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1532 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1533
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001535 injectMotionEvent(mDispatcher,
1536 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1537 .buttonState(0)
1538 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1539 .x(300)
1540 .y(400))
1541 .build()));
1542 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1543
1544 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001546 injectMotionEvent(mDispatcher,
1547 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1548 AINPUT_SOURCE_MOUSE)
1549 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1550 .x(900)
1551 .y(400))
1552 .build()));
1553 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1554 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1555 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1556 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1557 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1558 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1559}
1560
1561// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1562// directly in this test.
1563TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001565 sp<FakeWindowHandle> window =
1566 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1567 window->setFrame(Rect(0, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001568 window->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001569
1570 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1571
1572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1573
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001575 injectMotionEvent(mDispatcher,
1576 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1577 AINPUT_SOURCE_MOUSE)
1578 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1579 .x(300)
1580 .y(400))
1581 .build()));
1582 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1583 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1584
1585 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001587 injectMotionEvent(mDispatcher,
1588 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1589 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1590 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1591 .x(300)
1592 .y(400))
1593 .build()));
1594 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1595
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001597 injectMotionEvent(mDispatcher,
1598 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1599 AINPUT_SOURCE_MOUSE)
1600 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1601 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1602 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1603 .x(300)
1604 .y(400))
1605 .build()));
1606 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1607 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1608
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001610 injectMotionEvent(mDispatcher,
1611 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1612 AINPUT_SOURCE_MOUSE)
1613 .buttonState(0)
1614 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1615 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1616 .x(300)
1617 .y(400))
1618 .build()));
1619 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1620 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1621
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001623 injectMotionEvent(mDispatcher,
1624 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1625 .buttonState(0)
1626 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1627 .x(300)
1628 .y(400))
1629 .build()));
1630 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1631
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001633 injectMotionEvent(mDispatcher,
1634 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1635 AINPUT_SOURCE_MOUSE)
1636 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1637 .x(300)
1638 .y(400))
1639 .build()));
1640 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1641 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1642}
1643
Garfield Tan00f511d2019-06-12 16:55:40 -07001644TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001645 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001646
1647 sp<FakeWindowHandle> windowLeft =
1648 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1649 windowLeft->setFrame(Rect(0, 0, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001650 windowLeft->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001651 sp<FakeWindowHandle> windowRight =
1652 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1653 windowRight->setFrame(Rect(600, 0, 1200, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001654 windowRight->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001655
1656 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1657
Arthur Hung72d8dc32020-03-28 00:48:39 +00001658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001659
1660 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1661 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001663 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001664 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001665 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001666 windowRight->assertNoEvents();
1667}
1668
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001669TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001670 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001671 sp<FakeWindowHandle> window =
1672 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001673 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001674
Arthur Hung72d8dc32020-03-28 00:48:39 +00001675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001676 setFocusedWindow(window);
1677
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001678 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001679
1680 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1681 mDispatcher->notifyKey(&keyArgs);
1682
1683 // Window should receive key down event.
1684 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1685
1686 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1687 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001688 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001689 mDispatcher->notifyDeviceReset(&args);
1690 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1691 AKEY_EVENT_FLAG_CANCELED);
1692}
1693
1694TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001695 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001696 sp<FakeWindowHandle> window =
1697 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1698
Arthur Hung72d8dc32020-03-28 00:48:39 +00001699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001700
1701 NotifyMotionArgs motionArgs =
1702 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1703 ADISPLAY_ID_DEFAULT);
1704 mDispatcher->notifyMotion(&motionArgs);
1705
1706 // Window should receive motion down event.
1707 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1708
1709 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1710 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001711 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001712 mDispatcher->notifyDeviceReset(&args);
1713 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1714 0 /*expectedFlags*/);
1715}
1716
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001717using TransferFunction =
1718 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1719
1720class TransferTouchFixture : public InputDispatcherTest,
1721 public ::testing::WithParamInterface<TransferFunction> {};
1722
1723TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001724 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001725
1726 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001727 sp<FakeWindowHandle> firstWindow =
1728 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1729 sp<FakeWindowHandle> secondWindow =
1730 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001731
1732 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001734
1735 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001736 NotifyMotionArgs downMotionArgs =
1737 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1738 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001739 mDispatcher->notifyMotion(&downMotionArgs);
1740 // Only the first window should get the down event
1741 firstWindow->consumeMotionDown();
1742 secondWindow->assertNoEvents();
1743
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001744 // Transfer touch to the second window
1745 TransferFunction f = GetParam();
1746 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1747 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001748 // The first window gets cancel and the second gets down
1749 firstWindow->consumeMotionCancel();
1750 secondWindow->consumeMotionDown();
1751
1752 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001753 NotifyMotionArgs upMotionArgs =
1754 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1755 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001756 mDispatcher->notifyMotion(&upMotionArgs);
1757 // The first window gets no events and the second gets up
1758 firstWindow->assertNoEvents();
1759 secondWindow->consumeMotionUp();
1760}
1761
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001762TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001763 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001764
1765 PointF touchPoint = {10, 10};
1766
1767 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001768 sp<FakeWindowHandle> firstWindow =
1769 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1770 sp<FakeWindowHandle> secondWindow =
1771 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001772
1773 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001775
1776 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001777 NotifyMotionArgs downMotionArgs =
1778 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1779 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001780 mDispatcher->notifyMotion(&downMotionArgs);
1781 // Only the first window should get the down event
1782 firstWindow->consumeMotionDown();
1783 secondWindow->assertNoEvents();
1784
1785 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001786 NotifyMotionArgs pointerDownMotionArgs =
1787 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1788 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1789 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1790 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001791 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1792 // Only the first window should get the pointer down event
1793 firstWindow->consumeMotionPointerDown(1);
1794 secondWindow->assertNoEvents();
1795
1796 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001797 TransferFunction f = GetParam();
1798 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1799 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001800 // The first window gets cancel and the second gets down and pointer down
1801 firstWindow->consumeMotionCancel();
1802 secondWindow->consumeMotionDown();
1803 secondWindow->consumeMotionPointerDown(1);
1804
1805 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001806 NotifyMotionArgs pointerUpMotionArgs =
1807 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1808 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1809 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1810 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001811 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1812 // The first window gets nothing and the second gets pointer up
1813 firstWindow->assertNoEvents();
1814 secondWindow->consumeMotionPointerUp(1);
1815
1816 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001817 NotifyMotionArgs upMotionArgs =
1818 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1819 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001820 mDispatcher->notifyMotion(&upMotionArgs);
1821 // The first window gets nothing and the second gets up
1822 firstWindow->assertNoEvents();
1823 secondWindow->consumeMotionUp();
1824}
1825
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001826// For the cases of single pointer touch and two pointers non-split touch, the api's
1827// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1828// for the case where there are multiple pointers split across several windows.
1829INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1830 ::testing::Values(
1831 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
1832 sp<IBinder> destChannelToken) {
1833 return dispatcher->transferTouch(destChannelToken);
1834 },
1835 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
1836 sp<IBinder> to) {
1837 return dispatcher->transferTouchFocus(from, to,
1838 false /*isDragAndDrop*/);
1839 }));
1840
Svet Ganov5d3bc372020-01-26 23:11:07 -08001841TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001842 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001843
1844 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001845 sp<FakeWindowHandle> firstWindow =
1846 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001847 firstWindow->setFrame(Rect(0, 0, 600, 400));
Michael Wright44753b12020-07-08 13:48:11 +01001848 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1849 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001850
1851 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001852 sp<FakeWindowHandle> secondWindow =
1853 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001854 secondWindow->setFrame(Rect(0, 400, 600, 800));
Michael Wright44753b12020-07-08 13:48:11 +01001855 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1856 InputWindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001857
1858 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001860
1861 PointF pointInFirst = {300, 200};
1862 PointF pointInSecond = {300, 600};
1863
1864 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001865 NotifyMotionArgs firstDownMotionArgs =
1866 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1867 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001868 mDispatcher->notifyMotion(&firstDownMotionArgs);
1869 // Only the first window should get the down event
1870 firstWindow->consumeMotionDown();
1871 secondWindow->assertNoEvents();
1872
1873 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001874 NotifyMotionArgs secondDownMotionArgs =
1875 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1876 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1877 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1878 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001879 mDispatcher->notifyMotion(&secondDownMotionArgs);
1880 // The first window gets a move and the second a down
1881 firstWindow->consumeMotionMove();
1882 secondWindow->consumeMotionDown();
1883
1884 // Transfer touch focus to the second window
1885 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1886 // The first window gets cancel and the new gets pointer down (it already saw down)
1887 firstWindow->consumeMotionCancel();
1888 secondWindow->consumeMotionPointerDown(1);
1889
1890 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001891 NotifyMotionArgs pointerUpMotionArgs =
1892 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1893 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1894 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1895 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001896 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1897 // The first window gets nothing and the second gets pointer up
1898 firstWindow->assertNoEvents();
1899 secondWindow->consumeMotionPointerUp(1);
1900
1901 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001902 NotifyMotionArgs upMotionArgs =
1903 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1904 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001905 mDispatcher->notifyMotion(&upMotionArgs);
1906 // The first window gets nothing and the second gets up
1907 firstWindow->assertNoEvents();
1908 secondWindow->consumeMotionUp();
1909}
1910
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001911// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1912// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1913// touch is not supported, so the touch should continue on those windows and the transferred-to
1914// window should get nothing.
1915TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1916 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1917
1918 // Create a non touch modal window that supports split touch
1919 sp<FakeWindowHandle> firstWindow =
1920 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1921 firstWindow->setFrame(Rect(0, 0, 600, 400));
1922 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1923 InputWindowInfo::Flag::SPLIT_TOUCH);
1924
1925 // Create a non touch modal window that supports split touch
1926 sp<FakeWindowHandle> secondWindow =
1927 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1928 secondWindow->setFrame(Rect(0, 400, 600, 800));
1929 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
1930 InputWindowInfo::Flag::SPLIT_TOUCH);
1931
1932 // Add the windows to the dispatcher
1933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1934
1935 PointF pointInFirst = {300, 200};
1936 PointF pointInSecond = {300, 600};
1937
1938 // Send down to the first window
1939 NotifyMotionArgs firstDownMotionArgs =
1940 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1941 ADISPLAY_ID_DEFAULT, {pointInFirst});
1942 mDispatcher->notifyMotion(&firstDownMotionArgs);
1943 // Only the first window should get the down event
1944 firstWindow->consumeMotionDown();
1945 secondWindow->assertNoEvents();
1946
1947 // Send down to the second window
1948 NotifyMotionArgs secondDownMotionArgs =
1949 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1950 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1951 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1952 {pointInFirst, pointInSecond});
1953 mDispatcher->notifyMotion(&secondDownMotionArgs);
1954 // The first window gets a move and the second a down
1955 firstWindow->consumeMotionMove();
1956 secondWindow->consumeMotionDown();
1957
1958 // Transfer touch focus to the second window
1959 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1960 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1961 ASSERT_FALSE(transferred);
1962 firstWindow->assertNoEvents();
1963 secondWindow->assertNoEvents();
1964
1965 // The rest of the dispatch should proceed as normal
1966 // Send pointer up to the second window
1967 NotifyMotionArgs pointerUpMotionArgs =
1968 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1969 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1970 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1971 {pointInFirst, pointInSecond});
1972 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1973 // The first window gets MOVE and the second gets pointer up
1974 firstWindow->consumeMotionMove();
1975 secondWindow->consumeMotionUp();
1976
1977 // Send up event to the first window
1978 NotifyMotionArgs upMotionArgs =
1979 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1980 ADISPLAY_ID_DEFAULT);
1981 mDispatcher->notifyMotion(&upMotionArgs);
1982 // The first window gets nothing and the second gets up
1983 firstWindow->consumeMotionUp();
1984 secondWindow->assertNoEvents();
1985}
1986
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001987TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07001988 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001989 sp<FakeWindowHandle> window =
1990 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1991
Vishnu Nair47074b82020-08-14 11:54:47 -07001992 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00001993 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001994 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001995
1996 window->consumeFocusEvent(true);
1997
1998 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1999 mDispatcher->notifyKey(&keyArgs);
2000
2001 // Window should receive key down event.
2002 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2003}
2004
2005TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002006 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002007 sp<FakeWindowHandle> window =
2008 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2009
Arthur Hung72d8dc32020-03-28 00:48:39 +00002010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002011
2012 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2013 mDispatcher->notifyKey(&keyArgs);
2014 mDispatcher->waitForIdle();
2015
2016 window->assertNoEvents();
2017}
2018
2019// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2020TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002021 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002022 sp<FakeWindowHandle> window =
2023 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2024
Arthur Hung72d8dc32020-03-28 00:48:39 +00002025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002026
2027 // Send key
2028 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2029 mDispatcher->notifyKey(&keyArgs);
2030 // Send motion
2031 NotifyMotionArgs motionArgs =
2032 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2033 ADISPLAY_ID_DEFAULT);
2034 mDispatcher->notifyMotion(&motionArgs);
2035
2036 // Window should receive only the motion event
2037 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2038 window->assertNoEvents(); // Key event or focus event will not be received
2039}
2040
arthurhungea3f4fc2020-12-21 23:18:53 +08002041TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2042 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2043
2044 // Create first non touch modal window that supports split touch
2045 sp<FakeWindowHandle> firstWindow =
2046 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2047 firstWindow->setFrame(Rect(0, 0, 600, 400));
2048 firstWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2049 InputWindowInfo::Flag::SPLIT_TOUCH);
2050
2051 // Create second non touch modal window that supports split touch
2052 sp<FakeWindowHandle> secondWindow =
2053 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2054 secondWindow->setFrame(Rect(0, 400, 600, 800));
2055 secondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2056 InputWindowInfo::Flag::SPLIT_TOUCH);
2057
2058 // Add the windows to the dispatcher
2059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2060
2061 PointF pointInFirst = {300, 200};
2062 PointF pointInSecond = {300, 600};
2063
2064 // Send down to the first window
2065 NotifyMotionArgs firstDownMotionArgs =
2066 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2067 ADISPLAY_ID_DEFAULT, {pointInFirst});
2068 mDispatcher->notifyMotion(&firstDownMotionArgs);
2069 // Only the first window should get the down event
2070 firstWindow->consumeMotionDown();
2071 secondWindow->assertNoEvents();
2072
2073 // Send down to the second window
2074 NotifyMotionArgs secondDownMotionArgs =
2075 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2076 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2077 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2078 {pointInFirst, pointInSecond});
2079 mDispatcher->notifyMotion(&secondDownMotionArgs);
2080 // The first window gets a move and the second a down
2081 firstWindow->consumeMotionMove();
2082 secondWindow->consumeMotionDown();
2083
2084 // Send pointer cancel to the second window
2085 NotifyMotionArgs pointerUpMotionArgs =
2086 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2087 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2088 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2089 {pointInFirst, pointInSecond});
2090 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2091 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2092 // The first window gets move and the second gets cancel.
2093 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2094 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2095
2096 // Send up event.
2097 NotifyMotionArgs upMotionArgs =
2098 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2099 ADISPLAY_ID_DEFAULT);
2100 mDispatcher->notifyMotion(&upMotionArgs);
2101 // The first window gets up and the second gets nothing.
2102 firstWindow->consumeMotionUp();
2103 secondWindow->assertNoEvents();
2104}
2105
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002106TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2107 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2108
2109 sp<FakeWindowHandle> window =
2110 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2112 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2113 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2114 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2115
2116 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2117 window->assertNoEvents();
2118 mDispatcher->waitForIdle();
2119}
2120
chaviwd1c23182019-12-20 18:44:56 -08002121class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002122public:
2123 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002124 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002125 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002126 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002127 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002128 }
2129
chaviwd1c23182019-12-20 18:44:56 -08002130 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2131
2132 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2133 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2134 expectedDisplayId, expectedFlags);
2135 }
2136
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002137 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2138
2139 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2140
chaviwd1c23182019-12-20 18:44:56 -08002141 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2142 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2143 expectedDisplayId, expectedFlags);
2144 }
2145
2146 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2147 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2148 expectedDisplayId, expectedFlags);
2149 }
2150
Evan Rosky84f07f02021-04-16 10:42:42 -07002151 MotionEvent* consumeMotion() {
2152 InputEvent* event = mInputReceiver->consume();
2153 if (!event) {
2154 ADD_FAILURE() << "No event was produced";
2155 return nullptr;
2156 }
2157 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2158 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2159 return nullptr;
2160 }
2161 return static_cast<MotionEvent*>(event);
2162 }
2163
chaviwd1c23182019-12-20 18:44:56 -08002164 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2165
2166private:
2167 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002168};
2169
2170// Tests for gesture monitors
2171TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002172 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002173 sp<FakeWindowHandle> window =
2174 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002176
chaviwd1c23182019-12-20 18:44:56 -08002177 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2178 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002179
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002180 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002181 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002182 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002183 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002184 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002185}
2186
2187TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002188 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002189 sp<FakeWindowHandle> window =
2190 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2191
2192 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002193 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002194
Arthur Hung72d8dc32020-03-28 00:48:39 +00002195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002196 setFocusedWindow(window);
2197
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002198 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002199
chaviwd1c23182019-12-20 18:44:56 -08002200 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2201 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002202
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002203 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2204 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002205 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002206 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002207}
2208
2209TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002210 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002211 sp<FakeWindowHandle> window =
2212 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002214
chaviwd1c23182019-12-20 18:44:56 -08002215 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2216 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002217
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002219 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002220 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002221 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002222 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002223
2224 window->releaseChannel();
2225
chaviwd1c23182019-12-20 18:44:56 -08002226 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002227
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002229 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002230 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002231 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002232}
2233
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002234TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2235 FakeMonitorReceiver monitor =
2236 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2237 true /*isGestureMonitor*/);
2238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002239 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002240 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2241 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2242 ASSERT_TRUE(consumeSeq);
2243
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002244 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002245 monitor.finishEvent(*consumeSeq);
2246 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002247 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002248}
2249
Evan Rosky84f07f02021-04-16 10:42:42 -07002250// Tests for gesture monitors
2251TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2252 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2253 sp<FakeWindowHandle> window =
2254 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2256 window->setWindowOffset(20, 40);
2257 window->setWindowTransform(0, 1, -1, 0);
2258
2259 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2260 true /*isGestureMonitor*/);
2261
2262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2263 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2264 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2265 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2266 MotionEvent* event = monitor.consumeMotion();
2267 // Even though window has transform, gesture monitor must not.
2268 ASSERT_EQ(ui::Transform(), event->getTransform());
2269}
2270
chaviw81e2bb92019-12-18 15:03:51 -08002271TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002272 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002273 sp<FakeWindowHandle> window =
2274 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2275
Arthur Hung72d8dc32020-03-28 00:48:39 +00002276 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002277
2278 NotifyMotionArgs motionArgs =
2279 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2280 ADISPLAY_ID_DEFAULT);
2281
2282 mDispatcher->notifyMotion(&motionArgs);
2283 // Window should receive motion down event.
2284 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2285
2286 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002287 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002288 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2289 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2290 motionArgs.pointerCoords[0].getX() - 10);
2291
2292 mDispatcher->notifyMotion(&motionArgs);
2293 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2294 0 /*expectedFlags*/);
2295}
2296
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002297/**
2298 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2299 * the device default right away. In the test scenario, we check both the default value,
2300 * and the action of enabling / disabling.
2301 */
2302TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002303 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002304 sp<FakeWindowHandle> window =
2305 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2306
2307 // Set focused application.
2308 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002309 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002310
2311 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002313 setFocusedWindow(window);
2314
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002315 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2316
2317 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002318 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002320 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2321
2322 SCOPED_TRACE("Disable touch mode");
2323 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002324 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002326 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002327 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2328
2329 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002330 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002332 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2333
2334 SCOPED_TRACE("Enable touch mode again");
2335 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002336 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002338 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002339 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2340
2341 window->assertNoEvents();
2342}
2343
Gang Wange9087892020-01-07 12:17:14 -05002344TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002345 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002346 sp<FakeWindowHandle> window =
2347 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2348
2349 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002350 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002351
Arthur Hung72d8dc32020-03-28 00:48:39 +00002352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002353 setFocusedWindow(window);
2354
Gang Wange9087892020-01-07 12:17:14 -05002355 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2356
2357 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2358 mDispatcher->notifyKey(&keyArgs);
2359
2360 InputEvent* event = window->consume();
2361 ASSERT_NE(event, nullptr);
2362
2363 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2364 ASSERT_NE(verified, nullptr);
2365 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2366
2367 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2368 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2369 ASSERT_EQ(keyArgs.source, verified->source);
2370 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2371
2372 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2373
2374 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2375 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002376 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2377 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2378 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2379 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2380 ASSERT_EQ(0, verifiedKey.repeatCount);
2381}
2382
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002383TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002385 sp<FakeWindowHandle> window =
2386 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2387
2388 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2389
Arthur Hung72d8dc32020-03-28 00:48:39 +00002390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002391
2392 NotifyMotionArgs motionArgs =
2393 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2394 ADISPLAY_ID_DEFAULT);
2395 mDispatcher->notifyMotion(&motionArgs);
2396
2397 InputEvent* event = window->consume();
2398 ASSERT_NE(event, nullptr);
2399
2400 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2401 ASSERT_NE(verified, nullptr);
2402 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2403
2404 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2405 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2406 EXPECT_EQ(motionArgs.source, verified->source);
2407 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2408
2409 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2410
2411 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2412 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2413 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2414 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2415 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2416 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2417 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2418}
2419
Prabir Pradhanbd527712021-03-09 19:17:09 -08002420TEST_F(InputDispatcherTest, NonPointerMotionEvent_NotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002421 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2422 sp<FakeWindowHandle> window =
2423 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2424 const std::string name = window->getName();
2425
2426 // Window gets transformed by offset values.
2427 window->setWindowOffset(500.0f, 500.0f);
2428
2429 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2430 window->setFocusable(true);
2431
2432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2433
2434 // First, we set focused window so that focusedWindowHandle is not null.
2435 setFocusedWindow(window);
2436
2437 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2438 window->consumeFocusEvent(true);
2439
Prabir Pradhanbd527712021-03-09 19:17:09 -08002440 constexpr const std::array nonPointerSources = {AINPUT_SOURCE_TRACKBALL,
2441 AINPUT_SOURCE_MOUSE_RELATIVE,
2442 AINPUT_SOURCE_JOYSTICK};
2443 for (const int source : nonPointerSources) {
2444 // Notify motion with a non-pointer source.
2445 NotifyMotionArgs motionArgs =
2446 generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, source, ADISPLAY_ID_DEFAULT);
2447 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002448
Prabir Pradhanbd527712021-03-09 19:17:09 -08002449 InputEvent* event = window->consume();
2450 ASSERT_NE(event, nullptr);
2451 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
2452 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
2453 << " event, got " << inputEventTypeToString(event->getType()) << " event";
yunho.shinf4a80b82020-11-16 21:13:57 +09002454
Prabir Pradhanbd527712021-03-09 19:17:09 -08002455 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
2456 EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, motionEvent.getAction());
2457 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002458
Prabir Pradhanbd527712021-03-09 19:17:09 -08002459 float expectedX = motionArgs.pointerCoords[0].getX();
2460 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002461
Prabir Pradhanbd527712021-03-09 19:17:09 -08002462 // Ensure the axis values from the final motion event are not transformed.
2463 EXPECT_EQ(expectedX, motionEvent.getX(0))
2464 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2465 << motionEvent.getX(0);
2466 EXPECT_EQ(expectedY, motionEvent.getY(0))
2467 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2468 << motionEvent.getY(0);
2469 // Ensure the raw and transformed axis values for the motion event are the same.
2470 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2471 << "expected raw and transformed X-axis values to be equal";
2472 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2473 << "expected raw and transformed Y-axis values to be equal";
2474 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002475}
2476
chaviw09c8d2d2020-08-24 15:48:26 -07002477/**
2478 * Ensure that separate calls to sign the same data are generating the same key.
2479 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2480 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2481 * tests.
2482 */
2483TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2484 KeyEvent event = getTestKeyEvent();
2485 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2486
2487 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2488 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2489 ASSERT_EQ(hmac1, hmac2);
2490}
2491
2492/**
2493 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2494 */
2495TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2496 KeyEvent event = getTestKeyEvent();
2497 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2498 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2499
2500 verifiedEvent.deviceId += 1;
2501 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2502
2503 verifiedEvent.source += 1;
2504 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2505
2506 verifiedEvent.eventTimeNanos += 1;
2507 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2508
2509 verifiedEvent.displayId += 1;
2510 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2511
2512 verifiedEvent.action += 1;
2513 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2514
2515 verifiedEvent.downTimeNanos += 1;
2516 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2517
2518 verifiedEvent.flags += 1;
2519 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2520
2521 verifiedEvent.keyCode += 1;
2522 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2523
2524 verifiedEvent.scanCode += 1;
2525 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2526
2527 verifiedEvent.metaState += 1;
2528 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2529
2530 verifiedEvent.repeatCount += 1;
2531 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2532}
2533
Vishnu Nair958da932020-08-21 17:12:37 -07002534TEST_F(InputDispatcherTest, SetFocusedWindow) {
2535 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2536 sp<FakeWindowHandle> windowTop =
2537 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2538 sp<FakeWindowHandle> windowSecond =
2539 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2540 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2541
2542 // Top window is also focusable but is not granted focus.
2543 windowTop->setFocusable(true);
2544 windowSecond->setFocusable(true);
2545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2546 setFocusedWindow(windowSecond);
2547
2548 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2550 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002551
2552 // Focused window should receive event.
2553 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2554 windowTop->assertNoEvents();
2555}
2556
2557TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2558 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2559 sp<FakeWindowHandle> window =
2560 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2561 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2562
2563 window->setFocusable(true);
2564 // Release channel for window is no longer valid.
2565 window->releaseChannel();
2566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2567 setFocusedWindow(window);
2568
2569 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002570 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2571 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002572
2573 // window channel is invalid, so it should not receive any input event.
2574 window->assertNoEvents();
2575}
2576
2577TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2578 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2579 sp<FakeWindowHandle> window =
2580 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2581 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2582
2583 // Window is not focusable.
2584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2585 setFocusedWindow(window);
2586
2587 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002588 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2589 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002590
2591 // window is invalid, so it should not receive any input event.
2592 window->assertNoEvents();
2593}
2594
2595TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2596 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2597 sp<FakeWindowHandle> windowTop =
2598 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2599 sp<FakeWindowHandle> windowSecond =
2600 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2601 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2602
2603 windowTop->setFocusable(true);
2604 windowSecond->setFocusable(true);
2605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2606 setFocusedWindow(windowTop);
2607 windowTop->consumeFocusEvent(true);
2608
2609 setFocusedWindow(windowSecond, windowTop);
2610 windowSecond->consumeFocusEvent(true);
2611 windowTop->consumeFocusEvent(false);
2612
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2614 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002615
2616 // Focused window should receive event.
2617 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2618}
2619
2620TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2622 sp<FakeWindowHandle> windowTop =
2623 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2624 sp<FakeWindowHandle> windowSecond =
2625 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2626 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2627
2628 windowTop->setFocusable(true);
2629 windowSecond->setFocusable(true);
2630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2631 setFocusedWindow(windowSecond, windowTop);
2632
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002633 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2634 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002635
2636 // Event should be dropped.
2637 windowTop->assertNoEvents();
2638 windowSecond->assertNoEvents();
2639}
2640
2641TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2642 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2643 sp<FakeWindowHandle> window =
2644 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2645 sp<FakeWindowHandle> previousFocusedWindow =
2646 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2647 ADISPLAY_ID_DEFAULT);
2648 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2649
2650 window->setFocusable(true);
2651 previousFocusedWindow->setFocusable(true);
2652 window->setVisible(false);
2653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2654 setFocusedWindow(previousFocusedWindow);
2655 previousFocusedWindow->consumeFocusEvent(true);
2656
2657 // Requesting focus on invisible window takes focus from currently focused window.
2658 setFocusedWindow(window);
2659 previousFocusedWindow->consumeFocusEvent(false);
2660
2661 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002663 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002664 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002665
2666 // Window does not get focus event or key down.
2667 window->assertNoEvents();
2668
2669 // Window becomes visible.
2670 window->setVisible(true);
2671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2672
2673 // Window receives focus event.
2674 window->consumeFocusEvent(true);
2675 // Focused window receives key down.
2676 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2677}
2678
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002679/**
2680 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2681 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2682 * of the 'slipperyEnterWindow'.
2683 *
2684 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2685 * a way so that the touched location is no longer covered by the top window.
2686 *
2687 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2688 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2689 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2690 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2691 * with ACTION_DOWN).
2692 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2693 * window moved itself away from the touched location and had Flag::SLIPPERY.
2694 *
2695 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2696 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2697 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2698 *
2699 * In this test, we ensure that the event received by the bottom window has
2700 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2701 */
2702TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2703 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2704 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2705
2706 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2707 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2708
2709 sp<FakeWindowHandle> slipperyExitWindow =
2710 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2711 slipperyExitWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
2712 InputWindowInfo::Flag::SLIPPERY);
2713 // Make sure this one overlaps the bottom window
2714 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2715 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2716 // one. Windows with the same owner are not considered to be occluding each other.
2717 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2718
2719 sp<FakeWindowHandle> slipperyEnterWindow =
2720 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2721 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2722
2723 mDispatcher->setInputWindows(
2724 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2725
2726 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2727 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2728 ADISPLAY_ID_DEFAULT, {{50, 50}});
2729 mDispatcher->notifyMotion(&args);
2730 slipperyExitWindow->consumeMotionDown();
2731 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2732 mDispatcher->setInputWindows(
2733 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2734
2735 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2736 ADISPLAY_ID_DEFAULT, {{51, 51}});
2737 mDispatcher->notifyMotion(&args);
2738
2739 slipperyExitWindow->consumeMotionCancel();
2740
2741 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2742 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2743}
2744
Garfield Tan1c7bc862020-01-28 13:24:04 -08002745class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2746protected:
2747 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2748 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2749
Chris Yea209fde2020-07-22 13:54:51 -07002750 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002751 sp<FakeWindowHandle> mWindow;
2752
2753 virtual void SetUp() override {
2754 mFakePolicy = new FakeInputDispatcherPolicy();
2755 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2756 mDispatcher = new InputDispatcher(mFakePolicy);
2757 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2758 ASSERT_EQ(OK, mDispatcher->start());
2759
2760 setUpWindow();
2761 }
2762
2763 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002764 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002765 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2766
Vishnu Nair47074b82020-08-14 11:54:47 -07002767 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002769 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002770 mWindow->consumeFocusEvent(true);
2771 }
2772
Chris Ye2ad95392020-09-01 13:44:44 -07002773 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002774 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002775 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002776 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2777 mDispatcher->notifyKey(&keyArgs);
2778
2779 // Window should receive key down event.
2780 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2781 }
2782
2783 void expectKeyRepeatOnce(int32_t repeatCount) {
2784 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2785 InputEvent* repeatEvent = mWindow->consume();
2786 ASSERT_NE(nullptr, repeatEvent);
2787
2788 uint32_t eventType = repeatEvent->getType();
2789 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2790
2791 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2792 uint32_t eventAction = repeatKeyEvent->getAction();
2793 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2794 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2795 }
2796
Chris Ye2ad95392020-09-01 13:44:44 -07002797 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002798 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002799 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002800 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2801 mDispatcher->notifyKey(&keyArgs);
2802
2803 // Window should receive key down event.
2804 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2805 0 /*expectedFlags*/);
2806 }
2807};
2808
2809TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002810 sendAndConsumeKeyDown(1 /* deviceId */);
2811 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2812 expectKeyRepeatOnce(repeatCount);
2813 }
2814}
2815
2816TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2817 sendAndConsumeKeyDown(1 /* deviceId */);
2818 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2819 expectKeyRepeatOnce(repeatCount);
2820 }
2821 sendAndConsumeKeyDown(2 /* deviceId */);
2822 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002823 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2824 expectKeyRepeatOnce(repeatCount);
2825 }
2826}
2827
2828TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002829 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002830 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07002831 sendAndConsumeKeyUp(1 /* deviceId */);
2832 mWindow->assertNoEvents();
2833}
2834
2835TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
2836 sendAndConsumeKeyDown(1 /* deviceId */);
2837 expectKeyRepeatOnce(1 /*repeatCount*/);
2838 sendAndConsumeKeyDown(2 /* deviceId */);
2839 expectKeyRepeatOnce(1 /*repeatCount*/);
2840 // Stale key up from device 1.
2841 sendAndConsumeKeyUp(1 /* deviceId */);
2842 // Device 2 is still down, keep repeating
2843 expectKeyRepeatOnce(2 /*repeatCount*/);
2844 expectKeyRepeatOnce(3 /*repeatCount*/);
2845 // Device 2 key up
2846 sendAndConsumeKeyUp(2 /* deviceId */);
2847 mWindow->assertNoEvents();
2848}
2849
2850TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
2851 sendAndConsumeKeyDown(1 /* deviceId */);
2852 expectKeyRepeatOnce(1 /*repeatCount*/);
2853 sendAndConsumeKeyDown(2 /* deviceId */);
2854 expectKeyRepeatOnce(1 /*repeatCount*/);
2855 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
2856 sendAndConsumeKeyUp(2 /* deviceId */);
2857 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08002858 mWindow->assertNoEvents();
2859}
2860
liushenxiang42232912021-05-21 20:24:09 +08002861TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
2862 sendAndConsumeKeyDown(DEVICE_ID);
2863 expectKeyRepeatOnce(1 /*repeatCount*/);
2864 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
2865 mDispatcher->notifyDeviceReset(&args);
2866 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
2867 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
2868 mWindow->assertNoEvents();
2869}
2870
Garfield Tan1c7bc862020-01-28 13:24:04 -08002871TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07002872 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002873 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2874 InputEvent* repeatEvent = mWindow->consume();
2875 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2876 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
2877 IdGenerator::getSource(repeatEvent->getId()));
2878 }
2879}
2880
2881TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07002882 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002883
2884 std::unordered_set<int32_t> idSet;
2885 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2886 InputEvent* repeatEvent = mWindow->consume();
2887 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
2888 int32_t id = repeatEvent->getId();
2889 EXPECT_EQ(idSet.end(), idSet.find(id));
2890 idSet.insert(id);
2891 }
2892}
2893
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002894/* Test InputDispatcher for MultiDisplay */
2895class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
2896public:
2897 static constexpr int32_t SECOND_DISPLAY_ID = 1;
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002898 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002899 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08002900
Chris Yea209fde2020-07-22 13:54:51 -07002901 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002902 windowInPrimary =
2903 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002904
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002905 // Set focus window for primary display, but focused display would be second one.
2906 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07002907 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002909 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002910 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08002911
Chris Yea209fde2020-07-22 13:54:51 -07002912 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002913 windowInSecondary =
2914 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002915 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002916 // Set focus display to second one.
2917 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
2918 // Set focus window for second display.
2919 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07002920 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002921 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002922 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002923 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002924 }
2925
Prabir Pradhan3608aad2019-10-02 17:08:26 -07002926 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002927 InputDispatcherTest::TearDown();
2928
Chris Yea209fde2020-07-22 13:54:51 -07002929 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002930 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07002931 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002932 windowInSecondary.clear();
2933 }
2934
2935protected:
Chris Yea209fde2020-07-22 13:54:51 -07002936 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002937 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07002938 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002939 sp<FakeWindowHandle> windowInSecondary;
2940};
2941
2942TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
2943 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002947 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08002948 windowInSecondary->assertNoEvents();
2949
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002950 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
2953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002954 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002955 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08002956}
2957
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002958TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08002959 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002960 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2961 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002962 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002963 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08002964 windowInSecondary->assertNoEvents();
2965
2966 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002968 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08002969 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002970 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08002971
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08002972 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00002973 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08002974
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002975 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002976 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
2977 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08002978
2979 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08002980 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002981 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08002982 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002983 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08002984 windowInSecondary->assertNoEvents();
2985}
2986
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002987// Test per-display input monitors for motion event.
2988TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08002989 FakeMonitorReceiver monitorInPrimary =
2990 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
2991 FakeMonitorReceiver monitorInSecondary =
2992 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08002993
2994 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2996 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002998 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002999 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003000 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003001 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003002
3003 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003007 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003008 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003009 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003010 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003011
3012 // Test inject a non-pointer motion event.
3013 // If specific a display, it will dispatch to the focused window of particular display,
3014 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003018 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003019 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003020 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003021 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003022}
3023
3024// Test per-display input monitors for key event.
3025TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003026 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003027 FakeMonitorReceiver monitorInPrimary =
3028 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3029 FakeMonitorReceiver monitorInSecondary =
3030 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003031
3032 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3034 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003035 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003036 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003037 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003038 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003039}
3040
Vishnu Nair958da932020-08-21 17:12:37 -07003041TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3042 sp<FakeWindowHandle> secondWindowInPrimary =
3043 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3044 secondWindowInPrimary->setFocusable(true);
3045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3046 setFocusedWindow(secondWindowInPrimary);
3047 windowInPrimary->consumeFocusEvent(false);
3048 secondWindowInPrimary->consumeFocusEvent(true);
3049
3050 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3052 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003053 windowInPrimary->assertNoEvents();
3054 windowInSecondary->assertNoEvents();
3055 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3056}
3057
Jackal Guof9696682018-10-05 12:23:23 +08003058class InputFilterTest : public InputDispatcherTest {
3059protected:
3060 static constexpr int32_t SECOND_DISPLAY_ID = 1;
3061
3062 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3063 NotifyMotionArgs motionArgs;
3064
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003065 motionArgs =
3066 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003067 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003068 motionArgs =
3069 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003070 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003071 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003072 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003073 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003074 } else {
3075 mFakePolicy->assertFilterInputEventWasNotCalled();
3076 }
3077 }
3078
3079 void testNotifyKey(bool expectToBeFiltered) {
3080 NotifyKeyArgs keyArgs;
3081
3082 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3083 mDispatcher->notifyKey(&keyArgs);
3084 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3085 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003086 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003087
3088 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003089 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003090 } else {
3091 mFakePolicy->assertFilterInputEventWasNotCalled();
3092 }
3093 }
3094};
3095
3096// Test InputFilter for MotionEvent
3097TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3098 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3099 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3100 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3101
3102 // Enable InputFilter
3103 mDispatcher->setInputFilterEnabled(true);
3104 // Test touch on both primary and second display, and check if both events are filtered.
3105 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3106 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3107
3108 // Disable InputFilter
3109 mDispatcher->setInputFilterEnabled(false);
3110 // Test touch on both primary and second display, and check if both events aren't filtered.
3111 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3112 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3113}
3114
3115// Test InputFilter for KeyEvent
3116TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3117 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3118 testNotifyKey(/*expectToBeFiltered*/ false);
3119
3120 // Enable InputFilter
3121 mDispatcher->setInputFilterEnabled(true);
3122 // Send a key event, and check if it is filtered.
3123 testNotifyKey(/*expectToBeFiltered*/ true);
3124
3125 // Disable InputFilter
3126 mDispatcher->setInputFilterEnabled(false);
3127 // Send a key event, and check if it isn't filtered.
3128 testNotifyKey(/*expectToBeFiltered*/ false);
3129}
3130
chaviwfd6d3512019-03-25 13:23:49 -07003131class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003132 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003133 InputDispatcherTest::SetUp();
3134
Chris Yea209fde2020-07-22 13:54:51 -07003135 std::shared_ptr<FakeApplicationHandle> application =
3136 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003137 mUnfocusedWindow =
3138 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003139 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3140 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3141 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003142 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003143
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003144 mFocusedWindow =
3145 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3146 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003147 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003148
3149 // Set focused application.
3150 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003151 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003152
3153 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003155 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003156 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003157 }
3158
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003159 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003160 InputDispatcherTest::TearDown();
3161
3162 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003163 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003164 }
3165
3166protected:
3167 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003168 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003169 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003170};
3171
3172// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3173// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3174// the onPointerDownOutsideFocus callback.
3175TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003177 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3178 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003179 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003180 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003181
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003182 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003183 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3184}
3185
3186// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3187// DOWN on the window that doesn't have focus. Ensure no window received the
3188// onPointerDownOutsideFocus callback.
3189TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003191 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003192 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003193 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003194
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003195 ASSERT_TRUE(mDispatcher->waitForIdle());
3196 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003197}
3198
3199// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3200// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3201TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3203 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003204 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003205 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003206
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003207 ASSERT_TRUE(mDispatcher->waitForIdle());
3208 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003209}
3210
3211// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3212// DOWN on the window that already has focus. Ensure no window received the
3213// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003214TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003216 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003217 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003218 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003219 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003220
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003221 ASSERT_TRUE(mDispatcher->waitForIdle());
3222 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003223}
3224
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003225// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3226// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3227TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3228 const MotionEvent event =
3229 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3230 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3231 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3232 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3233 .build();
3234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3235 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3236 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3237
3238 ASSERT_TRUE(mDispatcher->waitForIdle());
3239 mFakePolicy->assertOnPointerDownWasNotCalled();
3240 // Ensure that the unfocused window did not receive any FOCUS events.
3241 mUnfocusedWindow->assertNoEvents();
3242}
3243
chaviwaf87b3e2019-10-01 16:59:28 -07003244// These tests ensures we can send touch events to a single client when there are multiple input
3245// windows that point to the same client token.
3246class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3247 virtual void SetUp() override {
3248 InputDispatcherTest::SetUp();
3249
Chris Yea209fde2020-07-22 13:54:51 -07003250 std::shared_ptr<FakeApplicationHandle> application =
3251 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003252 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3253 ADISPLAY_ID_DEFAULT);
3254 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3255 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
Michael Wright44753b12020-07-08 13:48:11 +01003256 mWindow1->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3257 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003258 mWindow1->setFrame(Rect(0, 0, 100, 100));
3259
3260 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3261 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Michael Wright44753b12020-07-08 13:48:11 +01003262 mWindow2->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3263 InputWindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003264 mWindow2->setFrame(Rect(100, 100, 200, 200));
3265
Arthur Hung72d8dc32020-03-28 00:48:39 +00003266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003267 }
3268
3269protected:
3270 sp<FakeWindowHandle> mWindow1;
3271 sp<FakeWindowHandle> mWindow2;
3272
3273 // Helper function to convert the point from screen coordinates into the window's space
3274 static PointF getPointInWindow(const InputWindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003275 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3276 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003277 }
3278
3279 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3280 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003281 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003282 InputEvent* event = window->consume();
3283
3284 ASSERT_NE(nullptr, event) << name.c_str()
3285 << ": consumer should have returned non-NULL event.";
3286
3287 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3288 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3289 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3290
3291 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3292 EXPECT_EQ(expectedAction, motionEvent.getAction());
3293
3294 for (size_t i = 0; i < points.size(); i++) {
3295 float expectedX = points[i].x;
3296 float expectedY = points[i].y;
3297
3298 EXPECT_EQ(expectedX, motionEvent.getX(i))
3299 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3300 << ", got " << motionEvent.getX(i);
3301 EXPECT_EQ(expectedY, motionEvent.getY(i))
3302 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3303 << ", got " << motionEvent.getY(i);
3304 }
3305 }
chaviw9eaa22c2020-07-01 16:21:27 -07003306
3307 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3308 std::vector<PointF> expectedPoints) {
3309 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3310 ADISPLAY_ID_DEFAULT, touchedPoints);
3311 mDispatcher->notifyMotion(&motionArgs);
3312
3313 // Always consume from window1 since it's the window that has the InputReceiver
3314 consumeMotionEvent(mWindow1, action, expectedPoints);
3315 }
chaviwaf87b3e2019-10-01 16:59:28 -07003316};
3317
3318TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3319 // Touch Window 1
3320 PointF touchedPoint = {10, 10};
3321 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003322 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003323
3324 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003325 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003326
3327 // Touch Window 2
3328 touchedPoint = {150, 150};
3329 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003330 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003331}
3332
chaviw9eaa22c2020-07-01 16:21:27 -07003333TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3334 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003335 mWindow2->setWindowScale(0.5f, 0.5f);
3336
3337 // Touch Window 1
3338 PointF touchedPoint = {10, 10};
3339 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003340 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003341 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003342 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003343
3344 // Touch Window 2
3345 touchedPoint = {150, 150};
3346 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003347 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3348 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003349
chaviw9eaa22c2020-07-01 16:21:27 -07003350 // Update the transform so rotation is set
3351 mWindow2->setWindowTransform(0, -1, 1, 0);
3352 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3353 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003354}
3355
chaviw9eaa22c2020-07-01 16:21:27 -07003356TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003357 mWindow2->setWindowScale(0.5f, 0.5f);
3358
3359 // Touch Window 1
3360 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3361 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003362 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003363
3364 // Touch Window 2
3365 int32_t actionPointerDown =
3366 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003367 touchedPoints.push_back(PointF{150, 150});
3368 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3369 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003370
chaviw9eaa22c2020-07-01 16:21:27 -07003371 // Release Window 2
3372 int32_t actionPointerUp =
3373 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3374 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3375 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003376
chaviw9eaa22c2020-07-01 16:21:27 -07003377 // Update the transform so rotation is set for Window 2
3378 mWindow2->setWindowTransform(0, -1, 1, 0);
3379 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3380 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003381}
3382
chaviw9eaa22c2020-07-01 16:21:27 -07003383TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003384 mWindow2->setWindowScale(0.5f, 0.5f);
3385
3386 // Touch Window 1
3387 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3388 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003389 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003390
3391 // Touch Window 2
3392 int32_t actionPointerDown =
3393 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003394 touchedPoints.push_back(PointF{150, 150});
3395 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003396
chaviw9eaa22c2020-07-01 16:21:27 -07003397 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003398
3399 // Move both windows
3400 touchedPoints = {{20, 20}, {175, 175}};
3401 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3402 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3403
chaviw9eaa22c2020-07-01 16:21:27 -07003404 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003405
chaviw9eaa22c2020-07-01 16:21:27 -07003406 // Release Window 2
3407 int32_t actionPointerUp =
3408 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3409 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3410 expectedPoints.pop_back();
3411
3412 // Touch Window 2
3413 mWindow2->setWindowTransform(0, -1, 1, 0);
3414 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3415 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3416
3417 // Move both windows
3418 touchedPoints = {{20, 20}, {175, 175}};
3419 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3420 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3421
3422 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003423}
3424
3425TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3426 mWindow1->setWindowScale(0.5f, 0.5f);
3427
3428 // Touch Window 1
3429 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3430 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003431 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003432
3433 // Touch Window 2
3434 int32_t actionPointerDown =
3435 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003436 touchedPoints.push_back(PointF{150, 150});
3437 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003438
chaviw9eaa22c2020-07-01 16:21:27 -07003439 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003440
3441 // Move both windows
3442 touchedPoints = {{20, 20}, {175, 175}};
3443 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3444 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3445
chaviw9eaa22c2020-07-01 16:21:27 -07003446 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003447}
3448
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003449class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3450 virtual void SetUp() override {
3451 InputDispatcherTest::SetUp();
3452
Chris Yea209fde2020-07-22 13:54:51 -07003453 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003454 mApplication->setDispatchingTimeout(20ms);
3455 mWindow =
3456 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3457 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003458 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003459 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003460 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3461 // window.
Michael Wright44753b12020-07-08 13:48:11 +01003462 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003463
3464 // Set focused application.
3465 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3466
3467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003468 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003469 mWindow->consumeFocusEvent(true);
3470 }
3471
3472 virtual void TearDown() override {
3473 InputDispatcherTest::TearDown();
3474 mWindow.clear();
3475 }
3476
3477protected:
Chris Yea209fde2020-07-22 13:54:51 -07003478 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003479 sp<FakeWindowHandle> mWindow;
3480 static constexpr PointF WINDOW_LOCATION = {20, 20};
3481
3482 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003484 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3485 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003487 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3488 WINDOW_LOCATION));
3489 }
3490};
3491
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003492// Send a tap and respond, which should not cause an ANR.
3493TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3494 tapOnWindow();
3495 mWindow->consumeMotionDown();
3496 mWindow->consumeMotionUp();
3497 ASSERT_TRUE(mDispatcher->waitForIdle());
3498 mFakePolicy->assertNotifyAnrWasNotCalled();
3499}
3500
3501// Send a regular key and respond, which should not cause an ANR.
3502TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003504 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3505 ASSERT_TRUE(mDispatcher->waitForIdle());
3506 mFakePolicy->assertNotifyAnrWasNotCalled();
3507}
3508
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003509TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3510 mWindow->setFocusable(false);
3511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3512 mWindow->consumeFocusEvent(false);
3513
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003514 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003515 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003516 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3517 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003519 // Key will not go to window because we have no focused window.
3520 // The 'no focused window' ANR timer should start instead.
3521
3522 // Now, the focused application goes away.
3523 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3524 // The key should get dropped and there should be no ANR.
3525
3526 ASSERT_TRUE(mDispatcher->waitForIdle());
3527 mFakePolicy->assertNotifyAnrWasNotCalled();
3528}
3529
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003530// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003531// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3532// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003533TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003535 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3536 WINDOW_LOCATION));
3537
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003538 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3539 ASSERT_TRUE(sequenceNum);
3540 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003541 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003542
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003543 mWindow->finishEvent(*sequenceNum);
3544 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3545 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003546 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003547 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003548}
3549
3550// Send a key to the app and have the app not respond right away.
3551TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3552 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003554 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3555 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003556 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003557 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003558 ASSERT_TRUE(mDispatcher->waitForIdle());
3559}
3560
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003561// We have a focused application, but no focused window
3562TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003563 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3565 mWindow->consumeFocusEvent(false);
3566
3567 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003569 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3570 WINDOW_LOCATION));
3571 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3572 mDispatcher->waitForIdle();
3573 mFakePolicy->assertNotifyAnrWasNotCalled();
3574
3575 // Once a focused event arrives, we get an ANR for this application
3576 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3577 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003578 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003579 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003580 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003581 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003582 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003583 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003584 ASSERT_TRUE(mDispatcher->waitForIdle());
3585}
3586
3587// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003588// Make sure that we don't notify policy twice about the same ANR.
3589TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003590 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3592 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003593
3594 // Once a focused event arrives, we get an ANR for this application
3595 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3596 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003597 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003598 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003599 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003600 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003601 const std::chrono::duration appTimeout =
3602 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003603 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003604
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003605 std::this_thread::sleep_for(appTimeout);
3606 // ANR should not be raised again. It is up to policy to do that if it desires.
3607 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003608
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003609 // If we now get a focused window, the ANR should stop, but the policy handles that via
3610 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003611 ASSERT_TRUE(mDispatcher->waitForIdle());
3612}
3613
3614// We have a focused application, but no focused window
3615TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003616 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3618 mWindow->consumeFocusEvent(false);
3619
3620 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003621 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003622 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003623 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3624 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003625
3626 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003627 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003628
3629 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003630 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003631 ASSERT_TRUE(mDispatcher->waitForIdle());
3632 mWindow->assertNoEvents();
3633}
3634
3635/**
3636 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3637 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3638 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3639 * the ANR mechanism should still work.
3640 *
3641 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3642 * DOWN event, while not responding on the second one.
3643 */
3644TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3645 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3646 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3647 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3648 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3649 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003650 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003651
3652 // Now send ACTION_UP, with identical timestamp
3653 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3654 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3655 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3656 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003657 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003658
3659 // We have now sent down and up. Let's consume first event and then ANR on the second.
3660 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3661 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003662 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003663}
3664
3665// If an app is not responding to a key event, gesture monitors should continue to receive
3666// new motion events
3667TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3668 FakeMonitorReceiver monitor =
3669 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3670 true /*isGestureMonitor*/);
3671
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3673 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003674 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003676
3677 // Stuck on the ACTION_UP
3678 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003679 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003680
3681 // New tap will go to the gesture monitor, but not to the window
3682 tapOnWindow();
3683 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3684 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3685
3686 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3687 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003688 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003689 mWindow->assertNoEvents();
3690 monitor.assertNoEvents();
3691}
3692
3693// If an app is not responding to a motion event, gesture monitors should continue to receive
3694// new motion events
3695TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3696 FakeMonitorReceiver monitor =
3697 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3698 true /*isGestureMonitor*/);
3699
3700 tapOnWindow();
3701 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3702 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3703
3704 mWindow->consumeMotionDown();
3705 // Stuck on the ACTION_UP
3706 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003707 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003708
3709 // New tap will go to the gesture monitor, but not to the window
3710 tapOnWindow();
3711 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3712 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3713
3714 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3715 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003716 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003717 mWindow->assertNoEvents();
3718 monitor.assertNoEvents();
3719}
3720
3721// If a window is unresponsive, then you get anr. if the window later catches up and starts to
3722// process events, you don't get an anr. When the window later becomes unresponsive again, you
3723// get an ANR again.
3724// 1. tap -> block on ACTION_UP -> receive ANR
3725// 2. consume all pending events (= queue becomes healthy again)
3726// 3. tap again -> block on ACTION_UP again -> receive ANR second time
3727TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
3728 tapOnWindow();
3729
3730 mWindow->consumeMotionDown();
3731 // Block on ACTION_UP
3732 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003733 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003734 mWindow->consumeMotionUp(); // Now the connection should be healthy again
3735 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003736 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003737 mWindow->assertNoEvents();
3738
3739 tapOnWindow();
3740 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003741 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003742 mWindow->consumeMotionUp();
3743
3744 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003745 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003746 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003747 mWindow->assertNoEvents();
3748}
3749
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003750// If a connection remains unresponsive for a while, make sure policy is only notified once about
3751// it.
3752TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3755 WINDOW_LOCATION));
3756
3757 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003758 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003759 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003760 // 'notifyConnectionUnresponsive' should only be called once per connection
3761 mFakePolicy->assertNotifyAnrWasNotCalled();
3762 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003763 mWindow->consumeMotionDown();
3764 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3765 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3766 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003767 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003768 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003769 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003770}
3771
3772/**
3773 * If a window is processing a motion event, and then a key event comes in, the key event should
3774 * not to to the focused window until the motion is processed.
3775 *
3776 * Warning!!!
3777 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
3778 * and the injection timeout that we specify when injecting the key.
3779 * We must have the injection timeout (10ms) be smaller than
3780 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
3781 *
3782 * If that value changes, this test should also change.
3783 */
3784TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
3785 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3787
3788 tapOnWindow();
3789 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3790 ASSERT_TRUE(downSequenceNum);
3791 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3792 ASSERT_TRUE(upSequenceNum);
3793 // Don't finish the events yet, and send a key
3794 // Injection will "succeed" because we will eventually give up and send the key to the focused
3795 // window even if motions are still being processed. But because the injection timeout is short,
3796 // we will receive INJECTION_TIMED_OUT as the result.
3797
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003798 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003799 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003800 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3801 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003802 // Key will not be sent to the window, yet, because the window is still processing events
3803 // and the key remains pending, waiting for the touch events to be processed
3804 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3805 ASSERT_FALSE(keySequenceNum);
3806
3807 std::this_thread::sleep_for(500ms);
3808 // if we wait long enough though, dispatcher will give up, and still send the key
3809 // to the focused window, even though we have not yet finished the motion event
3810 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3811 mWindow->finishEvent(*downSequenceNum);
3812 mWindow->finishEvent(*upSequenceNum);
3813}
3814
3815/**
3816 * If a window is processing a motion event, and then a key event comes in, the key event should
3817 * not go to the focused window until the motion is processed.
3818 * If then a new motion comes in, then the pending key event should be going to the currently
3819 * focused window right away.
3820 */
3821TEST_F(InputDispatcherSingleWindowAnr,
3822 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
3823 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
3824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3825
3826 tapOnWindow();
3827 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
3828 ASSERT_TRUE(downSequenceNum);
3829 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
3830 ASSERT_TRUE(upSequenceNum);
3831 // Don't finish the events yet, and send a key
3832 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003833 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003834 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003835 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003836 // At this point, key is still pending, and should not be sent to the application yet.
3837 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
3838 ASSERT_FALSE(keySequenceNum);
3839
3840 // Now tap down again. It should cause the pending key to go to the focused window right away.
3841 tapOnWindow();
3842 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
3843 // the other events yet. We can finish events in any order.
3844 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
3845 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
3846 mWindow->consumeMotionDown();
3847 mWindow->consumeMotionUp();
3848 mWindow->assertNoEvents();
3849}
3850
3851class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
3852 virtual void SetUp() override {
3853 InputDispatcherTest::SetUp();
3854
Chris Yea209fde2020-07-22 13:54:51 -07003855 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003856 mApplication->setDispatchingTimeout(10ms);
3857 mUnfocusedWindow =
3858 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
3859 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3860 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3861 // window.
3862 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Michael Wright44753b12020-07-08 13:48:11 +01003863 mUnfocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3864 InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
3865 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003866
3867 mFocusedWindow =
3868 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003869 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003870 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Michael Wright44753b12020-07-08 13:48:11 +01003871 mFocusedWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL |
3872 InputWindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003873
3874 // Set focused application.
3875 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07003876 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003877
3878 // Expect one focus window exist in display.
3879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003880 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003881 mFocusedWindow->consumeFocusEvent(true);
3882 }
3883
3884 virtual void TearDown() override {
3885 InputDispatcherTest::TearDown();
3886
3887 mUnfocusedWindow.clear();
3888 mFocusedWindow.clear();
3889 }
3890
3891protected:
Chris Yea209fde2020-07-22 13:54:51 -07003892 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003893 sp<FakeWindowHandle> mUnfocusedWindow;
3894 sp<FakeWindowHandle> mFocusedWindow;
3895 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
3896 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
3897 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
3898
3899 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
3900
3901 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
3902
3903private:
3904 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003906 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3907 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003909 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3910 location));
3911 }
3912};
3913
3914// If we have 2 windows that are both unresponsive, the one with the shortest timeout
3915// should be ANR'd first.
3916TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3919 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003921 mFocusedWindow->consumeMotionDown();
3922 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3923 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3924 // We consumed all events, so no ANR
3925 ASSERT_TRUE(mDispatcher->waitForIdle());
3926 mFakePolicy->assertNotifyAnrWasNotCalled();
3927
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003929 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3930 FOCUSED_WINDOW_LOCATION));
3931 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
3932 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003933
3934 const std::chrono::duration timeout =
3935 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003936 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003937 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
3938 // sequence to make it consistent
3939 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003940 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003941 mFocusedWindow->consumeMotionDown();
3942 // This cancel is generated because the connection was unresponsive
3943 mFocusedWindow->consumeMotionCancel();
3944 mFocusedWindow->assertNoEvents();
3945 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003946 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003947 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003948 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003949}
3950
3951// If we have 2 windows with identical timeouts that are both unresponsive,
3952// it doesn't matter which order they should have ANR.
3953// But we should receive ANR for both.
3954TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
3955 // Set the timeout for unfocused window to match the focused window
3956 mUnfocusedWindow->setDispatchingTimeout(10ms);
3957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
3958
3959 tapOnFocusedWindow();
3960 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003961 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
3962 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003963
3964 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003965 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
3966 mFocusedWindow->getToken() == anrConnectionToken2);
3967 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
3968 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003969
3970 ASSERT_TRUE(mDispatcher->waitForIdle());
3971 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003972
3973 mFocusedWindow->consumeMotionDown();
3974 mFocusedWindow->consumeMotionUp();
3975 mUnfocusedWindow->consumeMotionOutside();
3976
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003977 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
3978 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003979
3980 // Both applications should be marked as responsive, in any order
3981 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
3982 mFocusedWindow->getToken() == responsiveToken2);
3983 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
3984 mUnfocusedWindow->getToken() == responsiveToken2);
3985 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003986}
3987
3988// If a window is already not responding, the second tap on the same window should be ignored.
3989// We should also log an error to account for the dropped event (not tested here).
3990// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
3991TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
3992 tapOnFocusedWindow();
3993 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
3994 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
3995 // Receive the events, but don't respond
3996 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
3997 ASSERT_TRUE(downEventSequenceNum);
3998 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
3999 ASSERT_TRUE(upEventSequenceNum);
4000 const std::chrono::duration timeout =
4001 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004002 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004003
4004 // Tap once again
4005 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004006 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004007 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4008 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004009 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004010 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4011 FOCUSED_WINDOW_LOCATION));
4012 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4013 // valid touch target
4014 mUnfocusedWindow->assertNoEvents();
4015
4016 // Consume the first tap
4017 mFocusedWindow->finishEvent(*downEventSequenceNum);
4018 mFocusedWindow->finishEvent(*upEventSequenceNum);
4019 ASSERT_TRUE(mDispatcher->waitForIdle());
4020 // The second tap did not go to the focused window
4021 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004022 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004023 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004024 mFakePolicy->assertNotifyAnrWasNotCalled();
4025}
4026
4027// If you tap outside of all windows, there will not be ANR
4028TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004029 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004030 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4031 LOCATION_OUTSIDE_ALL_WINDOWS));
4032 ASSERT_TRUE(mDispatcher->waitForIdle());
4033 mFakePolicy->assertNotifyAnrWasNotCalled();
4034}
4035
4036// Since the focused window is paused, tapping on it should not produce any events
4037TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4038 mFocusedWindow->setPaused(true);
4039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4040
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004041 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004042 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4043 FOCUSED_WINDOW_LOCATION));
4044
4045 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4046 ASSERT_TRUE(mDispatcher->waitForIdle());
4047 // Should not ANR because the window is paused, and touches shouldn't go to it
4048 mFakePolicy->assertNotifyAnrWasNotCalled();
4049
4050 mFocusedWindow->assertNoEvents();
4051 mUnfocusedWindow->assertNoEvents();
4052}
4053
4054/**
4055 * If a window is processing a motion event, and then a key event comes in, the key event should
4056 * not to to the focused window until the motion is processed.
4057 * If a different window becomes focused at this time, the key should go to that window instead.
4058 *
4059 * Warning!!!
4060 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4061 * and the injection timeout that we specify when injecting the key.
4062 * We must have the injection timeout (10ms) be smaller than
4063 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4064 *
4065 * If that value changes, this test should also change.
4066 */
4067TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4068 // Set a long ANR timeout to prevent it from triggering
4069 mFocusedWindow->setDispatchingTimeout(2s);
4070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4071
4072 tapOnUnfocusedWindow();
4073 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4074 ASSERT_TRUE(downSequenceNum);
4075 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4076 ASSERT_TRUE(upSequenceNum);
4077 // Don't finish the events yet, and send a key
4078 // Injection will succeed because we will eventually give up and send the key to the focused
4079 // window even if motions are still being processed.
4080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004082 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004083 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004085 // Key will not be sent to the window, yet, because the window is still processing events
4086 // and the key remains pending, waiting for the touch events to be processed
4087 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4088 ASSERT_FALSE(keySequenceNum);
4089
4090 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004091 mFocusedWindow->setFocusable(false);
4092 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004094 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004095
4096 // Focus events should precede the key events
4097 mUnfocusedWindow->consumeFocusEvent(true);
4098 mFocusedWindow->consumeFocusEvent(false);
4099
4100 // Finish the tap events, which should unblock dispatcher
4101 mUnfocusedWindow->finishEvent(*downSequenceNum);
4102 mUnfocusedWindow->finishEvent(*upSequenceNum);
4103
4104 // Now that all queues are cleared and no backlog in the connections, the key event
4105 // can finally go to the newly focused "mUnfocusedWindow".
4106 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4107 mFocusedWindow->assertNoEvents();
4108 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004109 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004110}
4111
4112// When the touch stream is split across 2 windows, and one of them does not respond,
4113// then ANR should be raised and the touch should be canceled for the unresponsive window.
4114// The other window should not be affected by that.
4115TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4116 // Touch Window 1
4117 NotifyMotionArgs motionArgs =
4118 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4119 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4120 mDispatcher->notifyMotion(&motionArgs);
4121 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4122 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4123
4124 // Touch Window 2
4125 int32_t actionPointerDown =
4126 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4127
4128 motionArgs =
4129 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4130 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4131 mDispatcher->notifyMotion(&motionArgs);
4132
4133 const std::chrono::duration timeout =
4134 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004135 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004136
4137 mUnfocusedWindow->consumeMotionDown();
4138 mFocusedWindow->consumeMotionDown();
4139 // Focused window may or may not receive ACTION_MOVE
4140 // But it should definitely receive ACTION_CANCEL due to the ANR
4141 InputEvent* event;
4142 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4143 ASSERT_TRUE(moveOrCancelSequenceNum);
4144 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4145 ASSERT_NE(nullptr, event);
4146 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4147 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4148 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4149 mFocusedWindow->consumeMotionCancel();
4150 } else {
4151 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4152 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004153 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004154 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004155
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004156 mUnfocusedWindow->assertNoEvents();
4157 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004158 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004159}
4160
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004161/**
4162 * If we have no focused window, and a key comes in, we start the ANR timer.
4163 * The focused application should add a focused window before the timer runs out to prevent ANR.
4164 *
4165 * If the user touches another application during this time, the key should be dropped.
4166 * Next, if a new focused window comes in, without toggling the focused application,
4167 * then no ANR should occur.
4168 *
4169 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4170 * but in some cases the policy may not update the focused application.
4171 */
4172TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4173 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4174 std::make_shared<FakeApplicationHandle>();
4175 focusedApplication->setDispatchingTimeout(60ms);
4176 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4177 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4178 mFocusedWindow->setFocusable(false);
4179
4180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4181 mFocusedWindow->consumeFocusEvent(false);
4182
4183 // Send a key. The ANR timer should start because there is no focused window.
4184 // 'focusedApplication' will get blamed if this timer completes.
4185 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004186 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004187 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004188 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4189 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004190 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004191
4192 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4193 // then the injected touches won't cause the focused event to get dropped.
4194 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4195 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4196 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4197 // For this test, it means that the key would get delivered to the window once it becomes
4198 // focused.
4199 std::this_thread::sleep_for(10ms);
4200
4201 // Touch unfocused window. This should force the pending key to get dropped.
4202 NotifyMotionArgs motionArgs =
4203 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4204 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4205 mDispatcher->notifyMotion(&motionArgs);
4206
4207 // We do not consume the motion right away, because that would require dispatcher to first
4208 // process (== drop) the key event, and by that time, ANR will be raised.
4209 // Set the focused window first.
4210 mFocusedWindow->setFocusable(true);
4211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4212 setFocusedWindow(mFocusedWindow);
4213 mFocusedWindow->consumeFocusEvent(true);
4214 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4215 // to another application. This could be a bug / behaviour in the policy.
4216
4217 mUnfocusedWindow->consumeMotionDown();
4218
4219 ASSERT_TRUE(mDispatcher->waitForIdle());
4220 // Should not ANR because we actually have a focused window. It was just added too slowly.
4221 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4222}
4223
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004224// These tests ensure we cannot send touch events to a window that's positioned behind a window
4225// that has feature NO_INPUT_CHANNEL.
4226// Layout:
4227// Top (closest to user)
4228// mNoInputWindow (above all windows)
4229// mBottomWindow
4230// Bottom (furthest from user)
4231class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4232 virtual void SetUp() override {
4233 InputDispatcherTest::SetUp();
4234
4235 mApplication = std::make_shared<FakeApplicationHandle>();
4236 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4237 "Window without input channel", ADISPLAY_ID_DEFAULT,
4238 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4239
4240 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4241 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4242 // It's perfectly valid for this window to not have an associated input channel
4243
4244 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4245 ADISPLAY_ID_DEFAULT);
4246 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4247
4248 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4249 }
4250
4251protected:
4252 std::shared_ptr<FakeApplicationHandle> mApplication;
4253 sp<FakeWindowHandle> mNoInputWindow;
4254 sp<FakeWindowHandle> mBottomWindow;
4255};
4256
4257TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4258 PointF touchedPoint = {10, 10};
4259
4260 NotifyMotionArgs motionArgs =
4261 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4262 ADISPLAY_ID_DEFAULT, {touchedPoint});
4263 mDispatcher->notifyMotion(&motionArgs);
4264
4265 mNoInputWindow->assertNoEvents();
4266 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4267 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4268 // and therefore should prevent mBottomWindow from receiving touches
4269 mBottomWindow->assertNoEvents();
4270}
4271
4272/**
4273 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4274 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4275 */
4276TEST_F(InputDispatcherMultiWindowOcclusionTests,
4277 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4278 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4279 "Window with input channel and NO_INPUT_CHANNEL",
4280 ADISPLAY_ID_DEFAULT);
4281
4282 mNoInputWindow->setInputFeatures(InputWindowInfo::Feature::NO_INPUT_CHANNEL);
4283 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4285
4286 PointF touchedPoint = {10, 10};
4287
4288 NotifyMotionArgs motionArgs =
4289 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4290 ADISPLAY_ID_DEFAULT, {touchedPoint});
4291 mDispatcher->notifyMotion(&motionArgs);
4292
4293 mNoInputWindow->assertNoEvents();
4294 mBottomWindow->assertNoEvents();
4295}
4296
Vishnu Nair958da932020-08-21 17:12:37 -07004297class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4298protected:
4299 std::shared_ptr<FakeApplicationHandle> mApp;
4300 sp<FakeWindowHandle> mWindow;
4301 sp<FakeWindowHandle> mMirror;
4302
4303 virtual void SetUp() override {
4304 InputDispatcherTest::SetUp();
4305 mApp = std::make_shared<FakeApplicationHandle>();
4306 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4307 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4308 mWindow->getToken());
4309 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4310 mWindow->setFocusable(true);
4311 mMirror->setFocusable(true);
4312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4313 }
4314};
4315
4316TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4317 // Request focus on a mirrored window
4318 setFocusedWindow(mMirror);
4319
4320 // window gets focused
4321 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4323 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004324 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4325}
4326
4327// A focused & mirrored window remains focused only if the window and its mirror are both
4328// focusable.
4329TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4330 setFocusedWindow(mMirror);
4331
4332 // window gets focused
4333 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4335 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004336 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004337 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4338 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004339 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4340
4341 mMirror->setFocusable(false);
4342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4343
4344 // window loses focus since one of the windows associated with the token in not focusable
4345 mWindow->consumeFocusEvent(false);
4346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004347 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4348 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004349 mWindow->assertNoEvents();
4350}
4351
4352// A focused & mirrored window remains focused until the window and its mirror both become
4353// invisible.
4354TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4355 setFocusedWindow(mMirror);
4356
4357 // window gets focused
4358 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4360 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004361 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4363 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004364 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4365
4366 mMirror->setVisible(false);
4367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4368
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4370 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004371 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4373 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004374 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4375
4376 mWindow->setVisible(false);
4377 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4378
4379 // window loses focus only after all windows associated with the token become invisible.
4380 mWindow->consumeFocusEvent(false);
4381
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004382 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4383 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004384 mWindow->assertNoEvents();
4385}
4386
4387// A focused & mirrored window remains focused until both windows are removed.
4388TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4389 setFocusedWindow(mMirror);
4390
4391 // window gets focused
4392 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4394 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004395 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4397 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004398 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4399
4400 // single window is removed but the window token remains focused
4401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4402
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4404 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004405 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4407 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004408 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4409
4410 // Both windows are removed
4411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4412 mWindow->consumeFocusEvent(false);
4413
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4415 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004416 mWindow->assertNoEvents();
4417}
4418
4419// Focus request can be pending until one window becomes visible.
4420TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4421 // Request focus on an invisible mirror.
4422 mWindow->setVisible(false);
4423 mMirror->setVisible(false);
4424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4425 setFocusedWindow(mMirror);
4426
4427 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004429 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004430 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004431
4432 mMirror->setVisible(true);
4433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4434
4435 // window gets focused
4436 mWindow->consumeFocusEvent(true);
4437 // window gets the pending key event
4438 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4439}
Prabir Pradhan99987712020-11-10 18:43:05 -08004440
4441class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4442protected:
4443 std::shared_ptr<FakeApplicationHandle> mApp;
4444 sp<FakeWindowHandle> mWindow;
4445 sp<FakeWindowHandle> mSecondWindow;
4446
4447 void SetUp() override {
4448 InputDispatcherTest::SetUp();
4449 mApp = std::make_shared<FakeApplicationHandle>();
4450 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4451 mWindow->setFocusable(true);
4452 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4453 mSecondWindow->setFocusable(true);
4454
4455 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4457
4458 setFocusedWindow(mWindow);
4459 mWindow->consumeFocusEvent(true);
4460 }
4461
4462 void notifyPointerCaptureChanged(bool enabled) {
4463 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(enabled);
4464 mDispatcher->notifyPointerCaptureChanged(&args);
4465 }
4466
4467 void requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window, bool enabled) {
4468 mDispatcher->requestPointerCapture(window->getToken(), enabled);
4469 mFakePolicy->waitForSetPointerCapture(enabled);
4470 notifyPointerCaptureChanged(enabled);
4471 window->consumeCaptureEvent(enabled);
4472 }
4473};
4474
4475TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4476 // Ensure that capture cannot be obtained for unfocused windows.
4477 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4478 mFakePolicy->assertSetPointerCaptureNotCalled();
4479 mSecondWindow->assertNoEvents();
4480
4481 // Ensure that capture can be enabled from the focus window.
4482 requestAndVerifyPointerCapture(mWindow, true);
4483
4484 // Ensure that capture cannot be disabled from a window that does not have capture.
4485 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4486 mFakePolicy->assertSetPointerCaptureNotCalled();
4487
4488 // Ensure that capture can be disabled from the window with capture.
4489 requestAndVerifyPointerCapture(mWindow, false);
4490}
4491
4492TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
4493 requestAndVerifyPointerCapture(mWindow, true);
4494
4495 setFocusedWindow(mSecondWindow);
4496
4497 // Ensure that the capture disabled event was sent first.
4498 mWindow->consumeCaptureEvent(false);
4499 mWindow->consumeFocusEvent(false);
4500 mSecondWindow->consumeFocusEvent(true);
4501 mFakePolicy->waitForSetPointerCapture(false);
4502
4503 // Ensure that additional state changes from InputReader are not sent to the window.
4504 notifyPointerCaptureChanged(false);
4505 notifyPointerCaptureChanged(true);
4506 notifyPointerCaptureChanged(false);
4507 mWindow->assertNoEvents();
4508 mSecondWindow->assertNoEvents();
4509 mFakePolicy->assertSetPointerCaptureNotCalled();
4510}
4511
4512TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
4513 requestAndVerifyPointerCapture(mWindow, true);
4514
4515 // InputReader unexpectedly disables and enables pointer capture.
4516 notifyPointerCaptureChanged(false);
4517 notifyPointerCaptureChanged(true);
4518
4519 // Ensure that Pointer Capture is disabled.
Prabir Pradhan7d030382020-12-21 07:58:35 -08004520 mFakePolicy->waitForSetPointerCapture(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004521 mWindow->consumeCaptureEvent(false);
4522 mWindow->assertNoEvents();
4523}
4524
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004525TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4526 requestAndVerifyPointerCapture(mWindow, true);
4527
4528 // The first window loses focus.
4529 setFocusedWindow(mSecondWindow);
4530 mFakePolicy->waitForSetPointerCapture(false);
4531 mWindow->consumeCaptureEvent(false);
4532
4533 // Request Pointer Capture from the second window before the notification from InputReader
4534 // arrives.
4535 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4536 mFakePolicy->waitForSetPointerCapture(true);
4537
4538 // InputReader notifies Pointer Capture was disabled (because of the focus change).
4539 notifyPointerCaptureChanged(false);
4540
4541 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
4542 notifyPointerCaptureChanged(true);
4543
4544 mSecondWindow->consumeFocusEvent(true);
4545 mSecondWindow->consumeCaptureEvent(true);
4546}
4547
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004548class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4549protected:
4550 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004551
4552 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4553 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4554
4555 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4556 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4557
4558 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4559 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4560 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4561 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4562 MAXIMUM_OBSCURING_OPACITY);
4563
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004564 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004565 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004566 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004567
4568 sp<FakeWindowHandle> mTouchWindow;
4569
4570 virtual void SetUp() override {
4571 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004572 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004573 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4574 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4575 }
4576
4577 virtual void TearDown() override {
4578 InputDispatcherTest::TearDown();
4579 mTouchWindow.clear();
4580 }
4581
4582 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name,
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004583 os::TouchOcclusionMode mode, float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004584 sp<FakeWindowHandle> window = getWindow(uid, name);
4585 window->setFlags(InputWindowInfo::Flag::NOT_TOUCHABLE);
4586 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004587 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004588 return window;
4589 }
4590
4591 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4592 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4593 sp<FakeWindowHandle> window =
4594 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4595 // Generate an arbitrary PID based on the UID
4596 window->setOwnerInfo(1777 + (uid % 10000), uid);
4597 return window;
4598 }
4599
4600 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4601 NotifyMotionArgs args =
4602 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4603 ADISPLAY_ID_DEFAULT, points);
4604 mDispatcher->notifyMotion(&args);
4605 }
4606};
4607
4608TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004609 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004612
4613 touch();
4614
4615 mTouchWindow->assertNoEvents();
4616}
4617
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004618TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004619 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4620 const sp<FakeWindowHandle>& w =
4621 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4623
4624 touch();
4625
4626 mTouchWindow->assertNoEvents();
4627}
4628
4629TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004630 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4631 const sp<FakeWindowHandle>& w =
4632 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4633 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4634
4635 touch();
4636
4637 w->assertNoEvents();
4638}
4639
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004640TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004641 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004643
4644 touch();
4645
4646 mTouchWindow->consumeAnyMotionDown();
4647}
4648
4649TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004650 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004651 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004652 w->setFrame(Rect(0, 0, 50, 50));
4653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004654
4655 touch({PointF{100, 100}});
4656
4657 mTouchWindow->consumeAnyMotionDown();
4658}
4659
4660TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004661 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004662 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4664
4665 touch();
4666
4667 mTouchWindow->consumeAnyMotionDown();
4668}
4669
4670TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4671 const sp<FakeWindowHandle>& w =
4672 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004674
4675 touch();
4676
4677 mTouchWindow->consumeAnyMotionDown();
4678}
4679
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004680TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4681 const sp<FakeWindowHandle>& w =
4682 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4684
4685 touch();
4686
4687 w->assertNoEvents();
4688}
4689
4690/**
4691 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4692 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4693 * window, the occluding window will still receive ACTION_OUTSIDE event.
4694 */
4695TEST_F(InputDispatcherUntrustedTouchesTest,
4696 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4697 const sp<FakeWindowHandle>& w =
4698 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4699 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4701
4702 touch();
4703
4704 w->consumeMotionOutside();
4705}
4706
4707TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
4708 const sp<FakeWindowHandle>& w =
4709 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4710 w->addFlags(InputWindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
4711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4712
4713 touch();
4714
4715 InputEvent* event = w->consume();
4716 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
4717 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4718 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
4719 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
4720}
4721
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004722TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004723 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004724 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4725 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4727
4728 touch();
4729
4730 mTouchWindow->consumeAnyMotionDown();
4731}
4732
4733TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
4734 const sp<FakeWindowHandle>& w =
4735 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4736 MAXIMUM_OBSCURING_OPACITY);
4737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004738
4739 touch();
4740
4741 mTouchWindow->consumeAnyMotionDown();
4742}
4743
4744TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004745 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004746 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4747 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4749
4750 touch();
4751
4752 mTouchWindow->assertNoEvents();
4753}
4754
4755TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
4756 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
4757 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004758 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4759 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004760 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004761 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4762 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4764
4765 touch();
4766
4767 mTouchWindow->assertNoEvents();
4768}
4769
4770TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
4771 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
4772 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004773 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
4774 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004775 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004776 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
4777 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004778 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4779
4780 touch();
4781
4782 mTouchWindow->consumeAnyMotionDown();
4783}
4784
4785TEST_F(InputDispatcherUntrustedTouchesTest,
4786 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
4787 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004788 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4789 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004790 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004791 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4792 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4794
4795 touch();
4796
4797 mTouchWindow->consumeAnyMotionDown();
4798}
4799
4800TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
4801 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004802 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4803 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004804 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004805 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4806 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004808
4809 touch();
4810
4811 mTouchWindow->assertNoEvents();
4812}
4813
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004814TEST_F(InputDispatcherUntrustedTouchesTest,
4815 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
4816 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004817 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4818 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004819 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004820 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4821 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4823
4824 touch();
4825
4826 mTouchWindow->assertNoEvents();
4827}
4828
4829TEST_F(InputDispatcherUntrustedTouchesTest,
4830 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
4831 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004832 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4833 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004834 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004835 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4836 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
4838
4839 touch();
4840
4841 mTouchWindow->consumeAnyMotionDown();
4842}
4843
4844TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
4845 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004846 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
4847 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4849
4850 touch();
4851
4852 mTouchWindow->consumeAnyMotionDown();
4853}
4854
4855TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
4856 const sp<FakeWindowHandle>& w =
4857 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
4858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4859
4860 touch();
4861
4862 mTouchWindow->consumeAnyMotionDown();
4863}
4864
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004865TEST_F(InputDispatcherUntrustedTouchesTest,
4866 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
4867 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4868 const sp<FakeWindowHandle>& w =
4869 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
4870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4871
4872 touch();
4873
4874 mTouchWindow->assertNoEvents();
4875}
4876
4877TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
4878 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
4879 const sp<FakeWindowHandle>& w =
4880 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
4881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4882
4883 touch();
4884
4885 mTouchWindow->consumeAnyMotionDown();
4886}
4887
4888TEST_F(InputDispatcherUntrustedTouchesTest,
4889 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
4890 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
4891 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00004892 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4893 OPACITY_ABOVE_THRESHOLD);
4894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4895
4896 touch();
4897
4898 mTouchWindow->consumeAnyMotionDown();
4899}
4900
4901TEST_F(InputDispatcherUntrustedTouchesTest,
4902 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
4903 const sp<FakeWindowHandle>& w1 =
4904 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4905 OPACITY_BELOW_THRESHOLD);
4906 const sp<FakeWindowHandle>& w2 =
4907 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
4908 OPACITY_BELOW_THRESHOLD);
4909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
4910
4911 touch();
4912
4913 mTouchWindow->assertNoEvents();
4914}
4915
4916/**
4917 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
4918 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
4919 * (which alone would result in allowing touches) does not affect the blocking behavior.
4920 */
4921TEST_F(InputDispatcherUntrustedTouchesTest,
4922 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
4923 const sp<FakeWindowHandle>& wB =
4924 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
4925 OPACITY_BELOW_THRESHOLD);
4926 const sp<FakeWindowHandle>& wC =
4927 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
4928 OPACITY_BELOW_THRESHOLD);
4929 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
4930
4931 touch();
4932
4933 mTouchWindow->assertNoEvents();
4934}
4935
4936/**
4937 * This test is testing that a window from a different UID but with same application token doesn't
4938 * block the touch. Apps can share the application token for close UI collaboration for example.
4939 */
4940TEST_F(InputDispatcherUntrustedTouchesTest,
4941 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
4942 const sp<FakeWindowHandle>& w =
4943 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4944 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00004945 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4946
4947 touch();
4948
4949 mTouchWindow->consumeAnyMotionDown();
4950}
4951
arthurhungb89ccb02020-12-30 16:19:01 +08004952class InputDispatcherDragTests : public InputDispatcherTest {
4953protected:
4954 std::shared_ptr<FakeApplicationHandle> mApp;
4955 sp<FakeWindowHandle> mWindow;
4956 sp<FakeWindowHandle> mSecondWindow;
4957 sp<FakeWindowHandle> mDragWindow;
4958
4959 void SetUp() override {
4960 InputDispatcherTest::SetUp();
4961 mApp = std::make_shared<FakeApplicationHandle>();
4962 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4963 mWindow->setFrame(Rect(0, 0, 100, 100));
4964 mWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4965
4966 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4967 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
4968 mSecondWindow->setFlags(InputWindowInfo::Flag::NOT_TOUCH_MODAL);
4969
4970 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4972 }
4973
4974 // Start performing drag, we will create a drag window and transfer touch to it.
4975 void performDrag() {
4976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4977 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4978 {50, 50}))
4979 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4980
4981 // Window should receive motion event.
4982 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4983
4984 // The drag window covers the entire display
4985 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
4986 mDispatcher->setInputWindows(
4987 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
4988
4989 // Transfer touch focus to the drag window
4990 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
4991 true /* isDragDrop */);
4992 mWindow->consumeMotionCancel();
4993 mDragWindow->consumeMotionDown();
4994 }
arthurhung6d4bed92021-03-17 11:59:33 +08004995
4996 // Start performing drag, we will create a drag window and transfer touch to it.
4997 void performStylusDrag() {
4998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4999 injectMotionEvent(mDispatcher,
5000 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5001 AINPUT_SOURCE_STYLUS)
5002 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5003 .pointer(PointerBuilder(0,
5004 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5005 .x(50)
5006 .y(50))
5007 .build()));
5008 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5009
5010 // The drag window covers the entire display
5011 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5012 mDispatcher->setInputWindows(
5013 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5014
5015 // Transfer touch focus to the drag window
5016 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5017 true /* isDragDrop */);
5018 mWindow->consumeMotionCancel();
5019 mDragWindow->consumeMotionDown();
5020 }
arthurhungb89ccb02020-12-30 16:19:01 +08005021};
5022
5023TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5024 performDrag();
5025
5026 // Move on window.
5027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5028 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5029 ADISPLAY_ID_DEFAULT, {50, 50}))
5030 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5031 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5032 mWindow->consumeDragEvent(false, 50, 50);
5033 mSecondWindow->assertNoEvents();
5034
5035 // Move to another window.
5036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5037 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5038 ADISPLAY_ID_DEFAULT, {150, 50}))
5039 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5040 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5041 mWindow->consumeDragEvent(true, 150, 50);
5042 mSecondWindow->consumeDragEvent(false, 50, 50);
5043
5044 // Move back to original window.
5045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5046 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5047 ADISPLAY_ID_DEFAULT, {50, 50}))
5048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5049 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5050 mWindow->consumeDragEvent(false, 50, 50);
5051 mSecondWindow->consumeDragEvent(true, -50, 50);
5052
5053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5054 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5056 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5057 mWindow->assertNoEvents();
5058 mSecondWindow->assertNoEvents();
5059}
5060
arthurhungf452d0b2021-01-06 00:19:52 +08005061TEST_F(InputDispatcherDragTests, DragAndDrop) {
5062 performDrag();
5063
5064 // Move on window.
5065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5066 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5067 ADISPLAY_ID_DEFAULT, {50, 50}))
5068 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5069 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5070 mWindow->consumeDragEvent(false, 50, 50);
5071 mSecondWindow->assertNoEvents();
5072
5073 // Move to another window.
5074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5075 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5076 ADISPLAY_ID_DEFAULT, {150, 50}))
5077 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5078 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5079 mWindow->consumeDragEvent(true, 150, 50);
5080 mSecondWindow->consumeDragEvent(false, 50, 50);
5081
5082 // drop to another window.
5083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5084 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5085 {150, 50}))
5086 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5087 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5088 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5089 mWindow->assertNoEvents();
5090 mSecondWindow->assertNoEvents();
5091}
5092
arthurhung6d4bed92021-03-17 11:59:33 +08005093TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5094 performStylusDrag();
5095
5096 // Move on window and keep button pressed.
5097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5098 injectMotionEvent(mDispatcher,
5099 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5100 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5101 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5102 .x(50)
5103 .y(50))
5104 .build()))
5105 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5106 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5107 mWindow->consumeDragEvent(false, 50, 50);
5108 mSecondWindow->assertNoEvents();
5109
5110 // Move to another window and release button, expect to drop item.
5111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5112 injectMotionEvent(mDispatcher,
5113 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5114 .buttonState(0)
5115 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5116 .x(150)
5117 .y(50))
5118 .build()))
5119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5120 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5121 mWindow->assertNoEvents();
5122 mSecondWindow->assertNoEvents();
5123 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5124
5125 // nothing to the window.
5126 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5127 injectMotionEvent(mDispatcher,
5128 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5129 .buttonState(0)
5130 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5131 .x(150)
5132 .y(50))
5133 .build()))
5134 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5135 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5136 mWindow->assertNoEvents();
5137 mSecondWindow->assertNoEvents();
5138}
5139
Arthur Hung6d0571e2021-04-09 20:18:16 +08005140TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5141 performDrag();
5142
5143 // Set second window invisible.
5144 mSecondWindow->setVisible(false);
5145 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5146
5147 // Move on window.
5148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5149 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5150 ADISPLAY_ID_DEFAULT, {50, 50}))
5151 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5152 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5153 mWindow->consumeDragEvent(false, 50, 50);
5154 mSecondWindow->assertNoEvents();
5155
5156 // Move to another window.
5157 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5158 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5159 ADISPLAY_ID_DEFAULT, {150, 50}))
5160 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5161 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5162 mWindow->consumeDragEvent(true, 150, 50);
5163 mSecondWindow->assertNoEvents();
5164
5165 // drop to another window.
5166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5167 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5168 {150, 50}))
5169 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5170 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5171 mFakePolicy->assertDropTargetEquals(nullptr);
5172 mWindow->assertNoEvents();
5173 mSecondWindow->assertNoEvents();
5174}
5175
Garfield Tane84e6f92019-08-29 17:28:41 -07005176} // namespace android::inputdispatcher