blob: 0a91bde03bb1c6c9646482c5bc92654c6656d2c8 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -070019#include <android-base/properties.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080020#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070021#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070022#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080023#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100024#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <linux/input.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026
Garfield Tan1c7bc862020-01-28 13:24:04 -080027#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070028#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080029#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080030#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080031
Garfield Tan1c7bc862020-01-28 13:24:04 -080032using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050033using android::gui::FocusRequest;
34using android::gui::TouchOcclusionMode;
35using android::gui::WindowInfo;
36using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080037using android::os::InputEventInjectionResult;
38using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010039using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080040
Garfield Tane84e6f92019-08-29 17:28:41 -070041namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080042
43// An arbitrary time value.
44static const nsecs_t ARBITRARY_TIME = 1234;
45
46// An arbitrary device id.
47static const int32_t DEVICE_ID = 1;
48
Jeff Brownf086ddb2014-02-11 14:28:48 -080049// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000050static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
51static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080052
Michael Wrightd02c5b62014-02-10 15:10:22 -080053// An arbitrary injector pid / uid pair that has permission to inject events.
54static const int32_t INJECTOR_PID = 999;
55static const int32_t INJECTOR_UID = 1001;
56
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000057// An arbitrary pid of the gesture monitor window
58static constexpr int32_t MONITOR_PID = 2001;
59
chaviwd1c23182019-12-20 18:44:56 -080060struct PointF {
61 float x;
62 float y;
63};
Michael Wrightd02c5b62014-02-10 15:10:22 -080064
Gang Wang342c9272020-01-13 13:15:04 -050065/**
66 * Return a DOWN key event with KEYCODE_A.
67 */
68static KeyEvent getTestKeyEvent() {
69 KeyEvent event;
70
Garfield Tanfbe732e2020-01-24 11:26:14 -080071 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
72 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
73 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050074 return event;
75}
76
Michael Wrightd02c5b62014-02-10 15:10:22 -080077// --- FakeInputDispatcherPolicy ---
78
79class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
80 InputDispatcherConfiguration mConfig;
81
82protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100083 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080084
85public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100086 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080087
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080088 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080089 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_KEY, args.eventTime, args.action,
90 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080091 }
92
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080093 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args) {
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -080094 assertFilterInputEventWasCalled(AINPUT_EVENT_TYPE_MOTION, args.eventTime, args.action,
95 args.displayId);
Jackal Guof9696682018-10-05 12:23:23 +080096 }
97
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -070098 void assertFilterInputEventWasNotCalled() {
99 std::scoped_lock lock(mLock);
100 ASSERT_EQ(nullptr, mFilteredEvent);
101 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800103 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700104 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800105 ASSERT_TRUE(mConfigurationChangedTime)
106 << "Timed out waiting for configuration changed call";
107 ASSERT_EQ(*mConfigurationChangedTime, when);
108 mConfigurationChangedTime = std::nullopt;
109 }
110
111 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700112 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800113 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800114 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800115 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
116 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
117 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
118 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
119 mLastNotifySwitch = std::nullopt;
120 }
121
chaviwfd6d3512019-03-25 13:23:49 -0700122 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700123 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800124 ASSERT_EQ(touchedToken, mOnPointerDownToken);
125 mOnPointerDownToken.clear();
126 }
127
128 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700129 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800130 ASSERT_TRUE(mOnPointerDownToken == nullptr)
131 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700132 }
133
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700134 // This function must be called soon after the expected ANR timer starts,
135 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500136 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700137 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500138 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
139 std::shared_ptr<InputApplicationHandle> application;
140 { // acquire lock
141 std::unique_lock lock(mLock);
142 android::base::ScopedLockAssertion assumeLocked(mLock);
143 ASSERT_NO_FATAL_FAILURE(
144 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
145 } // release lock
146 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700147 }
148
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000149 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
150 const sp<IBinder>& expectedConnectionToken) {
151 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500152 ASSERT_EQ(expectedConnectionToken, connectionToken);
153 }
154
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000155 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
156 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500157 ASSERT_EQ(expectedConnectionToken, connectionToken);
158 }
159
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000160 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
161 int32_t pid = getUnresponsiveMonitorPid(timeout);
162 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500163 }
164
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000165 void assertNotifyMonitorResponsiveWasCalled() {
166 int32_t pid = getResponsiveMonitorPid();
167 ASSERT_EQ(MONITOR_PID, pid);
168 }
169
170 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500171 std::unique_lock lock(mLock);
172 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000173 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
174 }
175
176 sp<IBinder> getResponsiveWindowToken() {
177 std::unique_lock lock(mLock);
178 android::base::ScopedLockAssertion assumeLocked(mLock);
179 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
180 }
181
182 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
183 std::unique_lock lock(mLock);
184 android::base::ScopedLockAssertion assumeLocked(mLock);
185 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
186 }
187
188 int32_t getResponsiveMonitorPid() {
189 std::unique_lock lock(mLock);
190 android::base::ScopedLockAssertion assumeLocked(mLock);
191 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500192 }
193
194 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
195 // for a specific container to become non-empty. When the container is non-empty, return the
196 // first entry from the container and erase it.
197 template <class T>
198 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
199 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
200 const std::chrono::time_point start = std::chrono::steady_clock::now();
201 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700202
203 // If there is an ANR, Dispatcher won't be idle because there are still events
204 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
205 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500206 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
207 // to provide it some time to act. 100ms seems reasonable.
208 mNotifyAnr.wait_for(lock, timeToWait,
209 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700210 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500211 if (storage.empty()) {
212 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000213 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700214 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700215 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
216 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700217 if (std::chrono::abs(timeout - waited) > 100ms) {
218 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
219 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
220 << "ms, but waited "
221 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
222 << "ms instead";
223 }
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500224 T token = storage.front();
225 storage.pop();
226 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700227 }
228
229 void assertNotifyAnrWasNotCalled() {
230 std::scoped_lock lock(mLock);
231 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000232 ASSERT_TRUE(mAnrWindowTokens.empty());
233 ASSERT_TRUE(mAnrMonitorPids.empty());
234 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500235 << "ANR was not called, but please also consume the 'connection is responsive' "
236 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000237 ASSERT_TRUE(mResponsiveMonitorPids.empty())
238 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
239 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700240 }
241
Garfield Tan1c7bc862020-01-28 13:24:04 -0800242 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
243 mConfig.keyRepeatTimeout = timeout;
244 mConfig.keyRepeatDelay = delay;
245 }
246
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000247 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800248 std::unique_lock lock(mLock);
249 base::ScopedLockAssertion assumeLocked(mLock);
250
251 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
252 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000253 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800254 enabled;
255 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000256 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
257 << ") to be called.";
258 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800259 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000260 auto request = *mPointerCaptureRequest;
261 mPointerCaptureRequest.reset();
262 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800263 }
264
265 void assertSetPointerCaptureNotCalled() {
266 std::unique_lock lock(mLock);
267 base::ScopedLockAssertion assumeLocked(mLock);
268
269 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000270 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800271 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000272 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800273 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000274 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800275 }
276
arthurhungf452d0b2021-01-06 00:19:52 +0800277 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
278 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800279 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800280 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800281 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800282 }
283
Michael Wrightd02c5b62014-02-10 15:10:22 -0800284private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700285 std::mutex mLock;
286 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
287 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
288 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
289 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800290
Prabir Pradhan99987712020-11-10 18:43:05 -0800291 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000292
293 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800294
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700295 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700296 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000297 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
298 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
299 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
300 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700301 std::condition_variable mNotifyAnr;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700302
arthurhungf452d0b2021-01-06 00:19:52 +0800303 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800304 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800305
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600306 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700307 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800308 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 }
310
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000311 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700312 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000313 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700314 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500315 }
316
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000317 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500318 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000319 mAnrMonitorPids.push(pid);
320 mNotifyAnr.notify_all();
321 }
322
323 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
324 std::scoped_lock lock(mLock);
325 mResponsiveWindowTokens.push(connectionToken);
326 mNotifyAnr.notify_all();
327 }
328
329 void notifyMonitorResponsive(int32_t pid) override {
330 std::scoped_lock lock(mLock);
331 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500332 mNotifyAnr.notify_all();
333 }
334
335 void notifyNoFocusedWindowAnr(
336 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
337 std::scoped_lock lock(mLock);
338 mAnrApplications.push(applicationHandle);
339 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800340 }
341
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600342 void notifyInputChannelBroken(const sp<IBinder>&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800343
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600344 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700345
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600346 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700347 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
348 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
349 const std::vector<float>& values) override {}
350
351 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
352 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000353
Chris Yefb552902021-02-03 17:18:37 -0800354 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
355
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600356 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800357 *outConfig = mConfig;
358 }
359
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600360 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700361 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800362 switch (inputEvent->getType()) {
363 case AINPUT_EVENT_TYPE_KEY: {
364 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800365 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800366 break;
367 }
368
369 case AINPUT_EVENT_TYPE_MOTION: {
370 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800371 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800372 break;
373 }
374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800375 return true;
376 }
377
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600378 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800379
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600380 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800381
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600382 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800383 return 0;
384 }
385
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600386 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800387 return false;
388 }
389
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600390 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
391 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700392 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800393 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
394 * essentially a passthrough for notifySwitch.
395 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800396 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397 }
398
Sean Stoutb4e0a592021-02-23 07:34:53 -0800399 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800401 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
402 return pid == INJECTOR_PID && uid == INJECTOR_UID;
403 }
Jackal Guof9696682018-10-05 12:23:23 +0800404
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600405 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700406 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700407 mOnPointerDownToken = newToken;
408 }
409
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000410 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800411 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000412 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800413 mPointerCaptureChangedCondition.notify_all();
414 }
415
arthurhungf452d0b2021-01-06 00:19:52 +0800416 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
417 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800418 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800419 mDropTargetWindowToken = token;
420 }
421
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800422 void assertFilterInputEventWasCalled(int type, nsecs_t eventTime, int32_t action,
423 int32_t displayId) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700424 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800425 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
426 ASSERT_EQ(mFilteredEvent->getType(), type);
427
428 if (type == AINPUT_EVENT_TYPE_KEY) {
429 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*mFilteredEvent);
430 EXPECT_EQ(keyEvent.getEventTime(), eventTime);
431 EXPECT_EQ(keyEvent.getAction(), action);
432 EXPECT_EQ(keyEvent.getDisplayId(), displayId);
433 } else if (type == AINPUT_EVENT_TYPE_MOTION) {
434 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*mFilteredEvent);
435 EXPECT_EQ(motionEvent.getEventTime(), eventTime);
436 EXPECT_EQ(motionEvent.getAction(), action);
437 EXPECT_EQ(motionEvent.getDisplayId(), displayId);
438 } else {
439 FAIL() << "Unknown type: " << type;
440 }
441
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800442 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800443 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444};
445
Michael Wrightd02c5b62014-02-10 15:10:22 -0800446// --- InputDispatcherTest ---
447
448class InputDispatcherTest : public testing::Test {
449protected:
450 sp<FakeInputDispatcherPolicy> mFakePolicy;
451 sp<InputDispatcher> mDispatcher;
452
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000453 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 mFakePolicy = new FakeInputDispatcherPolicy();
455 mDispatcher = new InputDispatcher(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800456 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000457 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700458 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 }
460
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000461 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700462 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 mFakePolicy.clear();
464 mDispatcher.clear();
465 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700466
467 /**
468 * Used for debugging when writing the test
469 */
470 void dumpDispatcherState() {
471 std::string dump;
472 mDispatcher->dump(dump);
473 std::stringstream ss(dump);
474 std::string to;
475
476 while (std::getline(ss, to, '\n')) {
477 ALOGE("%s", to.c_str());
478 }
479 }
Vishnu Nair958da932020-08-21 17:12:37 -0700480
chaviw3277faf2021-05-19 16:45:23 -0500481 void setFocusedWindow(const sp<WindowInfoHandle>& window,
482 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700483 FocusRequest request;
484 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000485 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700486 if (focusedWindow) {
487 request.focusedToken = focusedWindow->getToken();
488 }
489 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
490 request.displayId = window->getInfo()->displayId;
491 mDispatcher->setFocusedWindow(request);
492 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493};
494
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
496 KeyEvent event;
497
498 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800499 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
500 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600501 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
502 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800503 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700504 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800505 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 << "Should reject key events with undefined action.";
507
508 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800509 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
510 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600511 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800512 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700513 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800514 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 << "Should reject key events with ACTION_MULTIPLE.";
516}
517
518TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
519 MotionEvent event;
520 PointerProperties pointerProperties[MAX_POINTERS + 1];
521 PointerCoords pointerCoords[MAX_POINTERS + 1];
522 for (int i = 0; i <= MAX_POINTERS; i++) {
523 pointerProperties[i].clear();
524 pointerProperties[i].id = i;
525 pointerCoords[i].clear();
526 }
527
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800528 // Some constants commonly used below
529 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
530 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
531 constexpr int32_t metaState = AMETA_NONE;
532 constexpr MotionClassification classification = MotionClassification::NONE;
533
chaviw9eaa22c2020-07-01 16:21:27 -0700534 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800536 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700537 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
538 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700539 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
540 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700541 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700543 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 << "Should reject motion events with undefined action.";
546
547 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800548 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700549 AMOTION_EVENT_ACTION_POINTER_DOWN |
550 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700551 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
552 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700553 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
554 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500555 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800556 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700557 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800558 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 << "Should reject motion events with pointer down index too large.";
560
Garfield Tanfbe732e2020-01-24 11:26:14 -0800561 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700562 AMOTION_EVENT_ACTION_POINTER_DOWN |
563 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700564 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
565 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700566 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
567 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500568 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800569 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700570 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800571 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 << "Should reject motion events with pointer down index too small.";
573
574 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800575 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700576 AMOTION_EVENT_ACTION_POINTER_UP |
577 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700578 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
579 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700580 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
581 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500582 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700584 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800585 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 << "Should reject motion events with pointer up index too large.";
587
Garfield Tanfbe732e2020-01-24 11:26:14 -0800588 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700589 AMOTION_EVENT_ACTION_POINTER_UP |
590 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700591 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
592 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700593 ui::Transform::ROT_0, INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE,
594 ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500595 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800596 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700597 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800598 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 << "Should reject motion events with pointer up index too small.";
600
601 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800602 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
603 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700604 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700605 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
606 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700607 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800608 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700609 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800610 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 << "Should reject motion events with 0 pointers.";
612
Garfield Tanfbe732e2020-01-24 11:26:14 -0800613 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
614 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700615 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700616 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
617 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700618 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800619 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700620 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800621 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 << "Should reject motion events with more than MAX_POINTERS pointers.";
623
624 // Rejects motion events with invalid pointer ids.
625 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800626 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
627 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700628 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700629 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
630 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700631 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800632 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700633 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 << "Should reject motion events with pointer ids less than 0.";
636
637 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800638 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
639 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700640 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700641 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
642 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800644 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700645 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800646 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
648
649 // Rejects motion events with duplicate pointer ids.
650 pointerProperties[0].id = 1;
651 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800652 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
653 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700654 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -0700655 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
656 INVALID_DISPLAY_SIZE, INVALID_DISPLAY_SIZE, ARBITRARY_TIME, ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700657 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800658 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700659 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 << "Should reject motion events with duplicate pointer ids.";
662}
663
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800664/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
665
666TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
667 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800668 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800669 mDispatcher->notifyConfigurationChanged(&args);
670 ASSERT_TRUE(mDispatcher->waitForIdle());
671
672 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
673}
674
675TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800676 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
677 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800678 mDispatcher->notifySwitch(&args);
679
680 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
681 args.policyFlags |= POLICY_FLAG_TRUSTED;
682 mFakePolicy->assertNotifySwitchWasCalled(args);
683}
684
Arthur Hungb92218b2018-08-14 12:00:21 +0800685// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700686static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700687// Default input dispatching timeout if there is no focused application or paused window
688// from which to determine an appropriate dispatching timeout.
689static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
690 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
691 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800692
693class FakeApplicationHandle : public InputApplicationHandle {
694public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700695 FakeApplicationHandle() {
696 mInfo.name = "Fake Application";
697 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500698 mInfo.dispatchingTimeoutMillis =
699 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700700 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800701 virtual ~FakeApplicationHandle() {}
702
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000703 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700704
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500705 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
706 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700707 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800708};
709
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800710class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800711public:
Garfield Tan15601662020-09-22 15:32:38 -0700712 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800713 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700714 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800715 }
716
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800717 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700718 InputEvent* event;
719 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
720 if (!consumeSeq) {
721 return nullptr;
722 }
723 finishEvent(*consumeSeq);
724 return event;
725 }
726
727 /**
728 * Receive an event without acknowledging it.
729 * Return the sequence number that could later be used to send finished signal.
730 */
731 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800732 uint32_t consumeSeq;
733 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800734
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800735 std::chrono::time_point start = std::chrono::steady_clock::now();
736 status_t status = WOULD_BLOCK;
737 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800738 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800739 &event);
740 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
741 if (elapsed > 100ms) {
742 break;
743 }
744 }
745
746 if (status == WOULD_BLOCK) {
747 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700748 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800749 }
750
751 if (status != OK) {
752 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700753 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800754 }
755 if (event == nullptr) {
756 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700757 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800758 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700759 if (outEvent != nullptr) {
760 *outEvent = event;
761 }
762 return consumeSeq;
763 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800764
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700765 /**
766 * To be used together with "receiveEvent" to complete the consumption of an event.
767 */
768 void finishEvent(uint32_t consumeSeq) {
769 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
770 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800771 }
772
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000773 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
774 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
775 ASSERT_EQ(OK, status);
776 }
777
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000778 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
779 std::optional<int32_t> expectedDisplayId,
780 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800781 InputEvent* event = consume();
782
783 ASSERT_NE(nullptr, event) << mName.c_str()
784 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800785 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700786 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800787 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800788
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000789 if (expectedDisplayId.has_value()) {
790 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
791 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800792
Tiger Huang8664f8c2018-10-11 19:14:35 +0800793 switch (expectedEventType) {
794 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800795 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
796 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000797 if (expectedFlags.has_value()) {
798 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
799 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800800 break;
801 }
802 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800803 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
804 EXPECT_EQ(expectedAction, motionEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000805 if (expectedFlags.has_value()) {
806 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
807 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800808 break;
809 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100810 case AINPUT_EVENT_TYPE_FOCUS: {
811 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
812 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800813 case AINPUT_EVENT_TYPE_CAPTURE: {
814 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
815 }
arthurhungb89ccb02020-12-30 16:19:01 +0800816 case AINPUT_EVENT_TYPE_DRAG: {
817 FAIL() << "Use 'consumeDragEvent' for DRAG events";
818 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800819 default: {
820 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
821 }
822 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800823 }
824
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100825 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
826 InputEvent* event = consume();
827 ASSERT_NE(nullptr, event) << mName.c_str()
828 << ": consumer should have returned non-NULL event.";
829 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
830 << "Got " << inputEventTypeToString(event->getType())
831 << " event instead of FOCUS event";
832
833 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
834 << mName.c_str() << ": event displayId should always be NONE.";
835
836 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
837 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
838 EXPECT_EQ(inTouchMode, focusEvent->getInTouchMode());
839 }
840
Prabir Pradhan99987712020-11-10 18:43:05 -0800841 void consumeCaptureEvent(bool hasCapture) {
842 const InputEvent* event = consume();
843 ASSERT_NE(nullptr, event) << mName.c_str()
844 << ": consumer should have returned non-NULL event.";
845 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
846 << "Got " << inputEventTypeToString(event->getType())
847 << " event instead of CAPTURE event";
848
849 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
850 << mName.c_str() << ": event displayId should always be NONE.";
851
852 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
853 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
854 }
855
arthurhungb89ccb02020-12-30 16:19:01 +0800856 void consumeDragEvent(bool isExiting, float x, float y) {
857 const InputEvent* event = consume();
858 ASSERT_NE(nullptr, event) << mName.c_str()
859 << ": consumer should have returned non-NULL event.";
860 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
861 << "Got " << inputEventTypeToString(event->getType())
862 << " event instead of DRAG event";
863
864 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
865 << mName.c_str() << ": event displayId should always be NONE.";
866
867 const auto& dragEvent = static_cast<const DragEvent&>(*event);
868 EXPECT_EQ(isExiting, dragEvent.isExiting());
869 EXPECT_EQ(x, dragEvent.getX());
870 EXPECT_EQ(y, dragEvent.getY());
871 }
872
chaviwd1c23182019-12-20 18:44:56 -0800873 void assertNoEvents() {
874 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700875 if (event == nullptr) {
876 return;
877 }
878 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
879 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
880 ADD_FAILURE() << "Received key event "
881 << KeyEvent::actionToString(keyEvent.getAction());
882 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
883 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
884 ADD_FAILURE() << "Received motion event "
885 << MotionEvent::actionToString(motionEvent.getAction());
886 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
887 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
888 ADD_FAILURE() << "Received focus event, hasFocus = "
889 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800890 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
891 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
892 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
893 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700894 }
895 FAIL() << mName.c_str()
896 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800897 }
898
899 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
900
901protected:
902 std::unique_ptr<InputConsumer> mConsumer;
903 PreallocatedInputEventFactory mEventFactory;
904
905 std::string mName;
906};
907
chaviw3277faf2021-05-19 16:45:23 -0500908class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800909public:
910 static const int32_t WIDTH = 600;
911 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800912
Chris Yea209fde2020-07-22 13:54:51 -0700913 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
chaviwd1c23182019-12-20 18:44:56 -0800914 const sp<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500915 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800916 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500917 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700918 base::Result<std::unique_ptr<InputChannel>> channel =
919 dispatcher->createInputChannel(name);
920 token = (*channel)->getConnectionToken();
921 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800922 }
923
924 inputApplicationHandle->updateInfo();
925 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
926
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500927 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700928 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800929 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500930 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500931 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000932 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800933 mInfo.frameLeft = 0;
934 mInfo.frameTop = 0;
935 mInfo.frameRight = WIDTH;
936 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700937 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800938 mInfo.globalScaleFactor = 1.0;
939 mInfo.touchableRegion.clear();
940 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
941 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -0700942 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -0800943 mInfo.hasWallpaper = false;
944 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -0800945 mInfo.ownerPid = INJECTOR_PID;
946 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800947 mInfo.displayId = displayId;
948 }
949
Arthur Hungabbb9d82021-09-01 14:52:30 +0000950 sp<FakeWindowHandle> clone(
951 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
952 const sp<InputDispatcher>& dispatcher, int32_t displayId) {
953 sp<FakeWindowHandle> handle =
954 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
955 displayId, mInfo.token);
956 return handle;
957 }
958
Vishnu Nair47074b82020-08-14 11:54:47 -0700959 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -0800960
Vishnu Nair958da932020-08-21 17:12:37 -0700961 void setVisible(bool visible) { mInfo.visible = visible; }
962
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700963 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500964 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700965 }
966
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700967 void setPaused(bool paused) { mInfo.paused = paused; }
968
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000969 void setAlpha(float alpha) { mInfo.alpha = alpha; }
970
chaviw3277faf2021-05-19 16:45:23 -0500971 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000972
Bernardo Rufino7393d172021-02-26 13:56:11 +0000973 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
974
chaviwd1c23182019-12-20 18:44:56 -0800975 void setFrame(const Rect& frame) {
976 mInfo.frameLeft = frame.left;
977 mInfo.frameTop = frame.top;
978 mInfo.frameRight = frame.right;
979 mInfo.frameBottom = frame.bottom;
arthurhungb89ccb02020-12-30 16:19:01 +0800980 mInfo.transform.set(-frame.left, -frame.top);
chaviwd1c23182019-12-20 18:44:56 -0800981 mInfo.touchableRegion.clear();
982 mInfo.addTouchableRegion(frame);
983 }
984
chaviw3277faf2021-05-19 16:45:23 -0500985 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +0000986
chaviw3277faf2021-05-19 16:45:23 -0500987 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -0800988
chaviw3277faf2021-05-19 16:45:23 -0500989 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500990
chaviw9eaa22c2020-07-01 16:21:27 -0700991 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
992 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
993 }
994
995 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -0700996
yunho.shinf4a80b82020-11-16 21:13:57 +0900997 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
998
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800999 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1000 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1001 expectedFlags);
1002 }
1003
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001004 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1005 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1006 }
1007
Svet Ganov5d3bc372020-01-26 23:11:07 -08001008 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001009 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001010 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1011 expectedFlags);
1012 }
1013
1014 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001015 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001016 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1017 expectedFlags);
1018 }
1019
1020 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001021 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001022 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1023 }
1024
1025 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1026 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001027 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1028 expectedFlags);
1029 }
1030
Svet Ganov5d3bc372020-01-26 23:11:07 -08001031 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001032 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1033 int32_t expectedFlags = 0) {
1034 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1035 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001036 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1037 }
1038
1039 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001040 int32_t expectedFlags = 0) {
1041 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1042 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001043 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1044 }
1045
1046 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001047 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001048 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1049 expectedFlags);
1050 }
1051
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001052 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1053 int32_t expectedFlags = 0) {
1054 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1055 expectedFlags);
1056 }
1057
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001058 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1059 ASSERT_NE(mInputReceiver, nullptr)
1060 << "Cannot consume events from a window with no receiver";
1061 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1062 }
1063
Prabir Pradhan99987712020-11-10 18:43:05 -08001064 void consumeCaptureEvent(bool hasCapture) {
1065 ASSERT_NE(mInputReceiver, nullptr)
1066 << "Cannot consume events from a window with no receiver";
1067 mInputReceiver->consumeCaptureEvent(hasCapture);
1068 }
1069
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001070 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1071 std::optional<int32_t> expectedDisplayId,
1072 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001073 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1074 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1075 expectedFlags);
1076 }
1077
arthurhungb89ccb02020-12-30 16:19:01 +08001078 void consumeDragEvent(bool isExiting, float x, float y) {
1079 mInputReceiver->consumeDragEvent(isExiting, x, y);
1080 }
1081
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001082 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001083 if (mInputReceiver == nullptr) {
1084 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1085 return std::nullopt;
1086 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001087 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001088 }
1089
1090 void finishEvent(uint32_t sequenceNum) {
1091 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1092 mInputReceiver->finishEvent(sequenceNum);
1093 }
1094
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001095 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1096 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1097 mInputReceiver->sendTimeline(inputEventId, timeline);
1098 }
1099
chaviwaf87b3e2019-10-01 16:59:28 -07001100 InputEvent* consume() {
1101 if (mInputReceiver == nullptr) {
1102 return nullptr;
1103 }
1104 return mInputReceiver->consume();
1105 }
1106
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001107 MotionEvent* consumeMotion() {
1108 InputEvent* event = consume();
1109 if (event == nullptr) {
1110 ADD_FAILURE() << "Consume failed : no event";
1111 return nullptr;
1112 }
1113 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1114 ADD_FAILURE() << "Instead of motion event, got "
1115 << inputEventTypeToString(event->getType());
1116 return nullptr;
1117 }
1118 return static_cast<MotionEvent*>(event);
1119 }
1120
Arthur Hungb92218b2018-08-14 12:00:21 +08001121 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001122 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001123 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001124 return; // Can't receive events if the window does not have input channel
1125 }
1126 ASSERT_NE(nullptr, mInputReceiver)
1127 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001128 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001129 }
1130
chaviwaf87b3e2019-10-01 16:59:28 -07001131 sp<IBinder> getToken() { return mInfo.token; }
1132
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001133 const std::string& getName() { return mName; }
1134
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001135 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1136 mInfo.ownerPid = ownerPid;
1137 mInfo.ownerUid = ownerUid;
1138 }
1139
chaviwd1c23182019-12-20 18:44:56 -08001140private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001142 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001143 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001144};
1145
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001146std::atomic<int32_t> FakeWindowHandle::sId{1};
1147
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001148static InputEventInjectionResult injectKey(
1149 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
1150 int32_t displayId = ADISPLAY_ID_NONE,
1151 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001152 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1153 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001154 KeyEvent event;
1155 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1156
1157 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001158 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001159 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1160 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001161
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001162 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1163 if (!allowKeyRepeat) {
1164 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1165 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001166 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001167 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001168 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001169}
1170
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001171static InputEventInjectionResult injectKeyDown(const sp<InputDispatcher>& dispatcher,
1172 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001173 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1174}
1175
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001176// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1177// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1178// has to be woken up to process the repeating key.
1179static InputEventInjectionResult injectKeyDownNoRepeat(const sp<InputDispatcher>& dispatcher,
1180 int32_t displayId = ADISPLAY_ID_NONE) {
1181 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1182 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1183 /* allowKeyRepeat */ false);
1184}
1185
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001186static InputEventInjectionResult injectKeyUp(const sp<InputDispatcher>& dispatcher,
1187 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001188 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1189}
1190
Garfield Tandf26e862020-07-01 20:18:19 -07001191class PointerBuilder {
1192public:
1193 PointerBuilder(int32_t id, int32_t toolType) {
1194 mProperties.clear();
1195 mProperties.id = id;
1196 mProperties.toolType = toolType;
1197 mCoords.clear();
1198 }
1199
1200 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1201
1202 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1203
1204 PointerBuilder& axis(int32_t axis, float value) {
1205 mCoords.setAxisValue(axis, value);
1206 return *this;
1207 }
1208
1209 PointerProperties buildProperties() const { return mProperties; }
1210
1211 PointerCoords buildCoords() const { return mCoords; }
1212
1213private:
1214 PointerProperties mProperties;
1215 PointerCoords mCoords;
1216};
1217
1218class MotionEventBuilder {
1219public:
1220 MotionEventBuilder(int32_t action, int32_t source) {
1221 mAction = action;
1222 mSource = source;
1223 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1224 }
1225
1226 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1227 mEventTime = eventTime;
1228 return *this;
1229 }
1230
1231 MotionEventBuilder& displayId(int32_t displayId) {
1232 mDisplayId = displayId;
1233 return *this;
1234 }
1235
1236 MotionEventBuilder& actionButton(int32_t actionButton) {
1237 mActionButton = actionButton;
1238 return *this;
1239 }
1240
arthurhung6d4bed92021-03-17 11:59:33 +08001241 MotionEventBuilder& buttonState(int32_t buttonState) {
1242 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001243 return *this;
1244 }
1245
1246 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1247 mRawXCursorPosition = rawXCursorPosition;
1248 return *this;
1249 }
1250
1251 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1252 mRawYCursorPosition = rawYCursorPosition;
1253 return *this;
1254 }
1255
1256 MotionEventBuilder& pointer(PointerBuilder pointer) {
1257 mPointers.push_back(pointer);
1258 return *this;
1259 }
1260
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001261 MotionEventBuilder& addFlag(uint32_t flags) {
1262 mFlags |= flags;
1263 return *this;
1264 }
1265
Garfield Tandf26e862020-07-01 20:18:19 -07001266 MotionEvent build() {
1267 std::vector<PointerProperties> pointerProperties;
1268 std::vector<PointerCoords> pointerCoords;
1269 for (const PointerBuilder& pointer : mPointers) {
1270 pointerProperties.push_back(pointer.buildProperties());
1271 pointerCoords.push_back(pointer.buildCoords());
1272 }
1273
1274 // Set mouse cursor position for the most common cases to avoid boilerplate.
1275 if (mSource == AINPUT_SOURCE_MOUSE &&
1276 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1277 mPointers.size() == 1) {
1278 mRawXCursorPosition = pointerCoords[0].getX();
1279 mRawYCursorPosition = pointerCoords[0].getY();
1280 }
1281
1282 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001283 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001284 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001285 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001286 mButtonState, MotionClassification::NONE, identityTransform,
1287 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Evan Rosky09576692021-07-01 12:22:09 -07001288 mRawYCursorPosition, mDisplayOrientation, mDisplayWidth, mDisplayHeight,
1289 mEventTime, mEventTime, mPointers.size(), pointerProperties.data(),
1290 pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001291
1292 return event;
1293 }
1294
1295private:
1296 int32_t mAction;
1297 int32_t mSource;
1298 nsecs_t mEventTime;
1299 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1300 int32_t mActionButton{0};
1301 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001302 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001303 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1304 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
Evan Rosky09576692021-07-01 12:22:09 -07001305 uint32_t mDisplayOrientation{ui::Transform::ROT_0};
chaviw3277faf2021-05-19 16:45:23 -05001306 int32_t mDisplayWidth{INVALID_DISPLAY_SIZE};
1307 int32_t mDisplayHeight{INVALID_DISPLAY_SIZE};
Garfield Tandf26e862020-07-01 20:18:19 -07001308
1309 std::vector<PointerBuilder> mPointers;
1310};
1311
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001312static InputEventInjectionResult injectMotionEvent(
Garfield Tandf26e862020-07-01 20:18:19 -07001313 const sp<InputDispatcher>& dispatcher, const MotionEvent& event,
1314 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001315 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001316 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1317 injectionTimeout,
1318 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1319}
1320
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001321static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001322 const sp<InputDispatcher>& dispatcher, int32_t action, int32_t source, int32_t displayId,
1323 const PointF& position,
1324 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001325 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1326 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001327 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001328 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001329 MotionEvent event = MotionEventBuilder(action, source)
1330 .displayId(displayId)
1331 .eventTime(eventTime)
1332 .rawXCursorPosition(cursorPosition.x)
1333 .rawYCursorPosition(cursorPosition.y)
1334 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1335 .x(position.x)
1336 .y(position.y))
1337 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001338
1339 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001340 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001341}
1342
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001343static InputEventInjectionResult injectMotionDown(const sp<InputDispatcher>& dispatcher,
1344 int32_t source, int32_t displayId,
1345 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001346 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001347}
1348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001349static InputEventInjectionResult injectMotionUp(const sp<InputDispatcher>& dispatcher,
1350 int32_t source, int32_t displayId,
1351 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001352 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001353}
1354
Jackal Guof9696682018-10-05 12:23:23 +08001355static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1356 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1357 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001358 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1359 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1360 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001361
1362 return args;
1363}
1364
chaviwd1c23182019-12-20 18:44:56 -08001365static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1366 const std::vector<PointF>& points) {
1367 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001368 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1369 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1370 }
1371
chaviwd1c23182019-12-20 18:44:56 -08001372 PointerProperties pointerProperties[pointerCount];
1373 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001374
chaviwd1c23182019-12-20 18:44:56 -08001375 for (size_t i = 0; i < pointerCount; i++) {
1376 pointerProperties[i].clear();
1377 pointerProperties[i].id = i;
1378 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001379
chaviwd1c23182019-12-20 18:44:56 -08001380 pointerCoords[i].clear();
1381 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1382 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1383 }
Jackal Guof9696682018-10-05 12:23:23 +08001384
1385 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1386 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001387 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001388 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1389 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001390 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1391 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001392 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1393 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001394
1395 return args;
1396}
1397
chaviwd1c23182019-12-20 18:44:56 -08001398static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1399 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1400}
1401
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001402static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1403 const PointerCaptureRequest& request) {
1404 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001405}
1406
Arthur Hungb92218b2018-08-14 12:00:21 +08001407TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001408 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001409 sp<FakeWindowHandle> window =
1410 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001411
Arthur Hung72d8dc32020-03-28 00:48:39 +00001412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1414 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001416
1417 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001418 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001419}
1420
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001421/**
1422 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1423 * To ensure that window receives only events that were directly inside of it, add
1424 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1425 * when finding touched windows.
1426 * This test serves as a sanity check for the next test, where setInputWindows is
1427 * called twice.
1428 */
1429TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001430 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001431 sp<FakeWindowHandle> window =
1432 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1433 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001434 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001435
1436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001438 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1439 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001440 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001441
1442 // Window should receive motion event.
1443 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1444}
1445
1446/**
1447 * Calling setInputWindows twice, with the same info, should not cause any issues.
1448 * To ensure that window receives only events that were directly inside of it, add
1449 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1450 * when finding touched windows.
1451 */
1452TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001453 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001454 sp<FakeWindowHandle> window =
1455 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1456 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001457 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001458
1459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1463 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001465
1466 // Window should receive motion event.
1467 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1468}
1469
Arthur Hungb92218b2018-08-14 12:00:21 +08001470// The foreground window should receive the first touch down event.
1471TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001472 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001473 sp<FakeWindowHandle> windowTop =
1474 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1475 sp<FakeWindowHandle> windowSecond =
1476 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001477
Arthur Hung72d8dc32020-03-28 00:48:39 +00001478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1480 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1481 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001482
1483 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001484 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001485 windowSecond->assertNoEvents();
1486}
1487
Garfield Tandf26e862020-07-01 20:18:19 -07001488TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001489 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001490 sp<FakeWindowHandle> windowLeft =
1491 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1492 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001493 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001494 sp<FakeWindowHandle> windowRight =
1495 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1496 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001497 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001498
1499 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1500
1501 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1502
1503 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001505 injectMotionEvent(mDispatcher,
1506 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1507 AINPUT_SOURCE_MOUSE)
1508 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1509 .x(900)
1510 .y(400))
1511 .build()));
1512 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1513 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1514 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1515 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1516
1517 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001519 injectMotionEvent(mDispatcher,
1520 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1521 AINPUT_SOURCE_MOUSE)
1522 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1523 .x(300)
1524 .y(400))
1525 .build()));
1526 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1527 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1528 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1529 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1530 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1531 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1532
1533 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1537 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1538 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1539 .x(300)
1540 .y(400))
1541 .build()));
1542 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1543
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001545 injectMotionEvent(mDispatcher,
1546 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1547 AINPUT_SOURCE_MOUSE)
1548 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1549 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1550 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1551 .x(300)
1552 .y(400))
1553 .build()));
1554 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1555 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1556
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001558 injectMotionEvent(mDispatcher,
1559 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1560 AINPUT_SOURCE_MOUSE)
1561 .buttonState(0)
1562 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1563 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1564 .x(300)
1565 .y(400))
1566 .build()));
1567 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1568 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1569
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001571 injectMotionEvent(mDispatcher,
1572 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1573 .buttonState(0)
1574 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1575 .x(300)
1576 .y(400))
1577 .build()));
1578 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1579
1580 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001582 injectMotionEvent(mDispatcher,
1583 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1584 AINPUT_SOURCE_MOUSE)
1585 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1586 .x(900)
1587 .y(400))
1588 .build()));
1589 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1590 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1591 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1592 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1593 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1594 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1595}
1596
1597// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1598// directly in this test.
1599TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001600 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001601 sp<FakeWindowHandle> window =
1602 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1603 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001604 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001605
1606 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1607
1608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1609
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001611 injectMotionEvent(mDispatcher,
1612 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1613 AINPUT_SOURCE_MOUSE)
1614 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1615 .x(300)
1616 .y(400))
1617 .build()));
1618 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1619 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1620
1621 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1625 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1626 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1627 .x(300)
1628 .y(400))
1629 .build()));
1630 window->consumeMotionDown(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_BUTTON_PRESS,
1635 AINPUT_SOURCE_MOUSE)
1636 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1637 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1638 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1639 .x(300)
1640 .y(400))
1641 .build()));
1642 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1643 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1644
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001645 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001646 injectMotionEvent(mDispatcher,
1647 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1648 AINPUT_SOURCE_MOUSE)
1649 .buttonState(0)
1650 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1651 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1652 .x(300)
1653 .y(400))
1654 .build()));
1655 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1656 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1657
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001659 injectMotionEvent(mDispatcher,
1660 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1661 .buttonState(0)
1662 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1663 .x(300)
1664 .y(400))
1665 .build()));
1666 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1667
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001669 injectMotionEvent(mDispatcher,
1670 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
1671 AINPUT_SOURCE_MOUSE)
1672 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1673 .x(300)
1674 .y(400))
1675 .build()));
1676 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1677 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1678}
1679
Garfield Tan00f511d2019-06-12 16:55:40 -07001680TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07001681 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07001682
1683 sp<FakeWindowHandle> windowLeft =
1684 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1685 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001686 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001687 sp<FakeWindowHandle> windowRight =
1688 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1689 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001690 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07001691
1692 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1693
Arthur Hung72d8dc32020-03-28 00:48:39 +00001694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07001695
1696 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
1697 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07001699 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001700 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001701 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07001702 windowRight->assertNoEvents();
1703}
1704
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001705TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001706 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001707 sp<FakeWindowHandle> window =
1708 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07001709 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001710
Arthur Hung72d8dc32020-03-28 00:48:39 +00001711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07001712 setFocusedWindow(window);
1713
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001714 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001715
1716 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
1717 mDispatcher->notifyKey(&keyArgs);
1718
1719 // Window should receive key down event.
1720 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
1721
1722 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
1723 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001724 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001725 mDispatcher->notifyDeviceReset(&args);
1726 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
1727 AKEY_EVENT_FLAG_CANCELED);
1728}
1729
1730TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07001731 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001732 sp<FakeWindowHandle> window =
1733 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1734
Arthur Hung72d8dc32020-03-28 00:48:39 +00001735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001736
1737 NotifyMotionArgs motionArgs =
1738 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1739 ADISPLAY_ID_DEFAULT);
1740 mDispatcher->notifyMotion(&motionArgs);
1741
1742 // Window should receive motion down event.
1743 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1744
1745 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
1746 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001747 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08001748 mDispatcher->notifyDeviceReset(&args);
1749 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
1750 0 /*expectedFlags*/);
1751}
1752
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001753using TransferFunction =
1754 std::function<bool(sp<InputDispatcher> dispatcher, sp<IBinder>, sp<IBinder>)>;
1755
1756class TransferTouchFixture : public InputDispatcherTest,
1757 public ::testing::WithParamInterface<TransferFunction> {};
1758
1759TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07001760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001761
1762 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001763 sp<FakeWindowHandle> firstWindow =
1764 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1765 sp<FakeWindowHandle> secondWindow =
1766 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001767
1768 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001770
1771 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001772 NotifyMotionArgs downMotionArgs =
1773 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1774 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001775 mDispatcher->notifyMotion(&downMotionArgs);
1776 // Only the first window should get the down event
1777 firstWindow->consumeMotionDown();
1778 secondWindow->assertNoEvents();
1779
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001780 // Transfer touch to the second window
1781 TransferFunction f = GetParam();
1782 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1783 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001784 // The first window gets cancel and the second gets down
1785 firstWindow->consumeMotionCancel();
1786 secondWindow->consumeMotionDown();
1787
1788 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001789 NotifyMotionArgs upMotionArgs =
1790 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1791 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001792 mDispatcher->notifyMotion(&upMotionArgs);
1793 // The first window gets no events and the second gets up
1794 firstWindow->assertNoEvents();
1795 secondWindow->consumeMotionUp();
1796}
1797
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001798TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001799 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001800
1801 PointF touchPoint = {10, 10};
1802
1803 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001804 sp<FakeWindowHandle> firstWindow =
1805 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1806 sp<FakeWindowHandle> secondWindow =
1807 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001808
1809 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001811
1812 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001813 NotifyMotionArgs downMotionArgs =
1814 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1815 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001816 mDispatcher->notifyMotion(&downMotionArgs);
1817 // Only the first window should get the down event
1818 firstWindow->consumeMotionDown();
1819 secondWindow->assertNoEvents();
1820
1821 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001822 NotifyMotionArgs pointerDownMotionArgs =
1823 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1824 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1825 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1826 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001827 mDispatcher->notifyMotion(&pointerDownMotionArgs);
1828 // Only the first window should get the pointer down event
1829 firstWindow->consumeMotionPointerDown(1);
1830 secondWindow->assertNoEvents();
1831
1832 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001833 TransferFunction f = GetParam();
1834 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
1835 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001836 // The first window gets cancel and the second gets down and pointer down
1837 firstWindow->consumeMotionCancel();
1838 secondWindow->consumeMotionDown();
1839 secondWindow->consumeMotionPointerDown(1);
1840
1841 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001842 NotifyMotionArgs pointerUpMotionArgs =
1843 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1844 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1845 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1846 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001847 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1848 // The first window gets nothing and the second gets pointer up
1849 firstWindow->assertNoEvents();
1850 secondWindow->consumeMotionPointerUp(1);
1851
1852 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001853 NotifyMotionArgs upMotionArgs =
1854 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1855 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001856 mDispatcher->notifyMotion(&upMotionArgs);
1857 // The first window gets nothing and the second gets up
1858 firstWindow->assertNoEvents();
1859 secondWindow->consumeMotionUp();
1860}
1861
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001862// For the cases of single pointer touch and two pointers non-split touch, the api's
1863// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
1864// for the case where there are multiple pointers split across several windows.
1865INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
1866 ::testing::Values(
1867 [&](sp<InputDispatcher> dispatcher, sp<IBinder> /*ignored*/,
1868 sp<IBinder> destChannelToken) {
1869 return dispatcher->transferTouch(destChannelToken);
1870 },
1871 [&](sp<InputDispatcher> dispatcher, sp<IBinder> from,
1872 sp<IBinder> to) {
1873 return dispatcher->transferTouchFocus(from, to,
1874 false /*isDragAndDrop*/);
1875 }));
1876
Svet Ganov5d3bc372020-01-26 23:11:07 -08001877TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001878 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08001879
1880 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001881 sp<FakeWindowHandle> firstWindow =
1882 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001883 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001884 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001885
1886 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001887 sp<FakeWindowHandle> secondWindow =
1888 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001889 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001890 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001891
1892 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00001893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001894
1895 PointF pointInFirst = {300, 200};
1896 PointF pointInSecond = {300, 600};
1897
1898 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001899 NotifyMotionArgs firstDownMotionArgs =
1900 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1901 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001902 mDispatcher->notifyMotion(&firstDownMotionArgs);
1903 // Only the first window should get the down event
1904 firstWindow->consumeMotionDown();
1905 secondWindow->assertNoEvents();
1906
1907 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001908 NotifyMotionArgs secondDownMotionArgs =
1909 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1910 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1911 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1912 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001913 mDispatcher->notifyMotion(&secondDownMotionArgs);
1914 // The first window gets a move and the second a down
1915 firstWindow->consumeMotionMove();
1916 secondWindow->consumeMotionDown();
1917
1918 // Transfer touch focus to the second window
1919 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
1920 // The first window gets cancel and the new gets pointer down (it already saw down)
1921 firstWindow->consumeMotionCancel();
1922 secondWindow->consumeMotionPointerDown(1);
1923
1924 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001925 NotifyMotionArgs pointerUpMotionArgs =
1926 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
1927 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1928 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1929 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08001930 mDispatcher->notifyMotion(&pointerUpMotionArgs);
1931 // The first window gets nothing and the second gets pointer up
1932 firstWindow->assertNoEvents();
1933 secondWindow->consumeMotionPointerUp(1);
1934
1935 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001936 NotifyMotionArgs upMotionArgs =
1937 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
1938 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001939 mDispatcher->notifyMotion(&upMotionArgs);
1940 // The first window gets nothing and the second gets up
1941 firstWindow->assertNoEvents();
1942 secondWindow->consumeMotionUp();
1943}
1944
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001945// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
1946// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
1947// touch is not supported, so the touch should continue on those windows and the transferred-to
1948// window should get nothing.
1949TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
1950 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1951
1952 // Create a non touch modal window that supports split touch
1953 sp<FakeWindowHandle> firstWindow =
1954 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
1955 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05001956 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001957
1958 // Create a non touch modal window that supports split touch
1959 sp<FakeWindowHandle> secondWindow =
1960 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
1961 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001962 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00001963
1964 // Add the windows to the dispatcher
1965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
1966
1967 PointF pointInFirst = {300, 200};
1968 PointF pointInSecond = {300, 600};
1969
1970 // Send down to the first window
1971 NotifyMotionArgs firstDownMotionArgs =
1972 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
1973 ADISPLAY_ID_DEFAULT, {pointInFirst});
1974 mDispatcher->notifyMotion(&firstDownMotionArgs);
1975 // Only the first window should get the down event
1976 firstWindow->consumeMotionDown();
1977 secondWindow->assertNoEvents();
1978
1979 // Send down to the second window
1980 NotifyMotionArgs secondDownMotionArgs =
1981 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
1982 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1983 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1984 {pointInFirst, pointInSecond});
1985 mDispatcher->notifyMotion(&secondDownMotionArgs);
1986 // The first window gets a move and the second a down
1987 firstWindow->consumeMotionMove();
1988 secondWindow->consumeMotionDown();
1989
1990 // Transfer touch focus to the second window
1991 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
1992 // The 'transferTouch' call should not succeed, because there are 2 touched windows
1993 ASSERT_FALSE(transferred);
1994 firstWindow->assertNoEvents();
1995 secondWindow->assertNoEvents();
1996
1997 // The rest of the dispatch should proceed as normal
1998 // Send pointer up to the second window
1999 NotifyMotionArgs pointerUpMotionArgs =
2000 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2001 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2002 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2003 {pointInFirst, pointInSecond});
2004 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2005 // The first window gets MOVE and the second gets pointer up
2006 firstWindow->consumeMotionMove();
2007 secondWindow->consumeMotionUp();
2008
2009 // Send up event to the first window
2010 NotifyMotionArgs upMotionArgs =
2011 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2012 ADISPLAY_ID_DEFAULT);
2013 mDispatcher->notifyMotion(&upMotionArgs);
2014 // The first window gets nothing and the second gets up
2015 firstWindow->consumeMotionUp();
2016 secondWindow->assertNoEvents();
2017}
2018
Arthur Hungabbb9d82021-09-01 14:52:30 +00002019// This case will create two windows and one mirrored window on the default display and mirror
2020// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2021// the windows info of second display before default display.
2022TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2023 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2024 sp<FakeWindowHandle> firstWindowInPrimary =
2025 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2026 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2027 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2028 sp<FakeWindowHandle> secondWindowInPrimary =
2029 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2030 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2031 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2032
2033 sp<FakeWindowHandle> mirrorWindowInPrimary =
2034 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2035 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2036 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2037
2038 sp<FakeWindowHandle> firstWindowInSecondary =
2039 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2040 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2041 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2042
2043 sp<FakeWindowHandle> secondWindowInSecondary =
2044 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2045 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2046 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2047
2048 // Update window info, let it find window handle of second display first.
2049 mDispatcher->setInputWindows(
2050 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2051 {ADISPLAY_ID_DEFAULT,
2052 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2053
2054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2055 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2056 {50, 50}))
2057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2058
2059 // Window should receive motion event.
2060 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2061
2062 // Transfer touch focus
2063 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2064 secondWindowInPrimary->getToken()));
2065 // The first window gets cancel.
2066 firstWindowInPrimary->consumeMotionCancel();
2067 secondWindowInPrimary->consumeMotionDown();
2068
2069 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2070 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2071 ADISPLAY_ID_DEFAULT, {150, 50}))
2072 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2073 firstWindowInPrimary->assertNoEvents();
2074 secondWindowInPrimary->consumeMotionMove();
2075
2076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2077 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2078 {150, 50}))
2079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2080 firstWindowInPrimary->assertNoEvents();
2081 secondWindowInPrimary->consumeMotionUp();
2082}
2083
2084// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2085// 'transferTouch' api.
2086TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2087 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2088 sp<FakeWindowHandle> firstWindowInPrimary =
2089 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2090 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2091 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2092 sp<FakeWindowHandle> secondWindowInPrimary =
2093 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2094 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2095 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2096
2097 sp<FakeWindowHandle> mirrorWindowInPrimary =
2098 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2099 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2100 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2101
2102 sp<FakeWindowHandle> firstWindowInSecondary =
2103 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2104 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2105 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2106
2107 sp<FakeWindowHandle> secondWindowInSecondary =
2108 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2109 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2110 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2111
2112 // Update window info, let it find window handle of second display first.
2113 mDispatcher->setInputWindows(
2114 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2115 {ADISPLAY_ID_DEFAULT,
2116 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2117
2118 // Touch on second display.
2119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2120 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2121 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2122
2123 // Window should receive motion event.
2124 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2125
2126 // Transfer touch focus
2127 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2128
2129 // The first window gets cancel.
2130 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2131 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2132
2133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2134 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2135 SECOND_DISPLAY_ID, {150, 50}))
2136 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2137 firstWindowInPrimary->assertNoEvents();
2138 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2139
2140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2141 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2142 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2143 firstWindowInPrimary->assertNoEvents();
2144 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2145}
2146
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002147TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002149 sp<FakeWindowHandle> window =
2150 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2151
Vishnu Nair47074b82020-08-14 11:54:47 -07002152 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002154 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002155
2156 window->consumeFocusEvent(true);
2157
2158 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2159 mDispatcher->notifyKey(&keyArgs);
2160
2161 // Window should receive key down event.
2162 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2163}
2164
2165TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002166 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002167 sp<FakeWindowHandle> window =
2168 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2169
Arthur Hung72d8dc32020-03-28 00:48:39 +00002170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002171
2172 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2173 mDispatcher->notifyKey(&keyArgs);
2174 mDispatcher->waitForIdle();
2175
2176 window->assertNoEvents();
2177}
2178
2179// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2180TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002181 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002182 sp<FakeWindowHandle> window =
2183 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2184
Arthur Hung72d8dc32020-03-28 00:48:39 +00002185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002186
2187 // Send key
2188 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2189 mDispatcher->notifyKey(&keyArgs);
2190 // Send motion
2191 NotifyMotionArgs motionArgs =
2192 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2193 ADISPLAY_ID_DEFAULT);
2194 mDispatcher->notifyMotion(&motionArgs);
2195
2196 // Window should receive only the motion event
2197 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2198 window->assertNoEvents(); // Key event or focus event will not be received
2199}
2200
arthurhungea3f4fc2020-12-21 23:18:53 +08002201TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2202 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2203
2204 // Create first non touch modal window that supports split touch
2205 sp<FakeWindowHandle> firstWindow =
2206 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2207 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002208 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002209
2210 // Create second non touch modal window that supports split touch
2211 sp<FakeWindowHandle> secondWindow =
2212 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2213 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002214 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002215
2216 // Add the windows to the dispatcher
2217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2218
2219 PointF pointInFirst = {300, 200};
2220 PointF pointInSecond = {300, 600};
2221
2222 // Send down to the first window
2223 NotifyMotionArgs firstDownMotionArgs =
2224 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2225 ADISPLAY_ID_DEFAULT, {pointInFirst});
2226 mDispatcher->notifyMotion(&firstDownMotionArgs);
2227 // Only the first window should get the down event
2228 firstWindow->consumeMotionDown();
2229 secondWindow->assertNoEvents();
2230
2231 // Send down to the second window
2232 NotifyMotionArgs secondDownMotionArgs =
2233 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2234 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2235 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2236 {pointInFirst, pointInSecond});
2237 mDispatcher->notifyMotion(&secondDownMotionArgs);
2238 // The first window gets a move and the second a down
2239 firstWindow->consumeMotionMove();
2240 secondWindow->consumeMotionDown();
2241
2242 // Send pointer cancel to the second window
2243 NotifyMotionArgs pointerUpMotionArgs =
2244 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2245 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2246 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2247 {pointInFirst, pointInSecond});
2248 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2249 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2250 // The first window gets move and the second gets cancel.
2251 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2252 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2253
2254 // Send up event.
2255 NotifyMotionArgs upMotionArgs =
2256 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2257 ADISPLAY_ID_DEFAULT);
2258 mDispatcher->notifyMotion(&upMotionArgs);
2259 // The first window gets up and the second gets nothing.
2260 firstWindow->consumeMotionUp();
2261 secondWindow->assertNoEvents();
2262}
2263
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002264TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2265 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2266
2267 sp<FakeWindowHandle> window =
2268 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2270 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2271 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2272 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2273
2274 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2275 window->assertNoEvents();
2276 mDispatcher->waitForIdle();
2277}
2278
chaviwd1c23182019-12-20 18:44:56 -08002279class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002280public:
2281 FakeMonitorReceiver(const sp<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002282 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002283 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002284 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002285 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002286 }
2287
chaviwd1c23182019-12-20 18:44:56 -08002288 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2289
2290 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2291 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2292 expectedDisplayId, expectedFlags);
2293 }
2294
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002295 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2296
2297 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2298
chaviwd1c23182019-12-20 18:44:56 -08002299 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2300 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2301 expectedDisplayId, expectedFlags);
2302 }
2303
2304 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2305 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2306 expectedDisplayId, expectedFlags);
2307 }
2308
Evan Rosky84f07f02021-04-16 10:42:42 -07002309 MotionEvent* consumeMotion() {
2310 InputEvent* event = mInputReceiver->consume();
2311 if (!event) {
2312 ADD_FAILURE() << "No event was produced";
2313 return nullptr;
2314 }
2315 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2316 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2317 return nullptr;
2318 }
2319 return static_cast<MotionEvent*>(event);
2320 }
2321
chaviwd1c23182019-12-20 18:44:56 -08002322 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2323
2324private:
2325 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002326};
2327
2328// Tests for gesture monitors
2329TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002330 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002331 sp<FakeWindowHandle> window =
2332 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002334
chaviwd1c23182019-12-20 18:44:56 -08002335 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2336 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002337
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002339 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002340 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002341 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002342 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002343}
2344
2345TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002346 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002347 sp<FakeWindowHandle> window =
2348 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2349
2350 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002351 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002352
Arthur Hung72d8dc32020-03-28 00:48:39 +00002353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002354 setFocusedWindow(window);
2355
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002356 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002357
chaviwd1c23182019-12-20 18:44:56 -08002358 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2359 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002360
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2362 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002363 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002364 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002365}
2366
2367TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002368 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002369 sp<FakeWindowHandle> window =
2370 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002372
chaviwd1c23182019-12-20 18:44:56 -08002373 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2374 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002375
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002377 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002378 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002379 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002380 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002381
2382 window->releaseChannel();
2383
chaviwd1c23182019-12-20 18:44:56 -08002384 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002385
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002386 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002387 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002389 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002390}
2391
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002392TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2393 FakeMonitorReceiver monitor =
2394 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2395 true /*isGestureMonitor*/);
2396
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002398 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2399 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2400 ASSERT_TRUE(consumeSeq);
2401
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002402 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002403 monitor.finishEvent(*consumeSeq);
2404 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002405 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002406}
2407
Evan Rosky84f07f02021-04-16 10:42:42 -07002408// Tests for gesture monitors
2409TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2410 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2411 sp<FakeWindowHandle> window =
2412 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2414 window->setWindowOffset(20, 40);
2415 window->setWindowTransform(0, 1, -1, 0);
2416
2417 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2418 true /*isGestureMonitor*/);
2419
2420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2421 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2422 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2423 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2424 MotionEvent* event = monitor.consumeMotion();
2425 // Even though window has transform, gesture monitor must not.
2426 ASSERT_EQ(ui::Transform(), event->getTransform());
2427}
2428
chaviw81e2bb92019-12-18 15:03:51 -08002429TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002430 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002431 sp<FakeWindowHandle> window =
2432 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2433
Arthur Hung72d8dc32020-03-28 00:48:39 +00002434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002435
2436 NotifyMotionArgs motionArgs =
2437 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2438 ADISPLAY_ID_DEFAULT);
2439
2440 mDispatcher->notifyMotion(&motionArgs);
2441 // Window should receive motion down event.
2442 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2443
2444 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002445 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002446 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2447 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2448 motionArgs.pointerCoords[0].getX() - 10);
2449
2450 mDispatcher->notifyMotion(&motionArgs);
2451 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2452 0 /*expectedFlags*/);
2453}
2454
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002455/**
2456 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2457 * the device default right away. In the test scenario, we check both the default value,
2458 * and the action of enabling / disabling.
2459 */
2460TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002461 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002462 sp<FakeWindowHandle> window =
2463 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2464
2465 // Set focused application.
2466 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002467 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002468
2469 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002470 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002471 setFocusedWindow(window);
2472
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002473 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2474
2475 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002476 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002477 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002478 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
2479
2480 SCOPED_TRACE("Disable touch mode");
2481 mDispatcher->setInTouchMode(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07002482 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002483 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002484 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002485 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
2486
2487 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002488 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002490 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
2491
2492 SCOPED_TRACE("Enable touch mode again");
2493 mDispatcher->setInTouchMode(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07002494 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002496 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002497 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2498
2499 window->assertNoEvents();
2500}
2501
Gang Wange9087892020-01-07 12:17:14 -05002502TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05002504 sp<FakeWindowHandle> window =
2505 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2506
2507 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002508 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05002509
Arthur Hung72d8dc32020-03-28 00:48:39 +00002510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002511 setFocusedWindow(window);
2512
Gang Wange9087892020-01-07 12:17:14 -05002513 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2514
2515 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
2516 mDispatcher->notifyKey(&keyArgs);
2517
2518 InputEvent* event = window->consume();
2519 ASSERT_NE(event, nullptr);
2520
2521 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2522 ASSERT_NE(verified, nullptr);
2523 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
2524
2525 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
2526 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
2527 ASSERT_EQ(keyArgs.source, verified->source);
2528 ASSERT_EQ(keyArgs.displayId, verified->displayId);
2529
2530 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
2531
2532 ASSERT_EQ(keyArgs.action, verifiedKey.action);
2533 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05002534 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
2535 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
2536 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
2537 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
2538 ASSERT_EQ(0, verifiedKey.repeatCount);
2539}
2540
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002541TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002542 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002543 sp<FakeWindowHandle> window =
2544 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2545
2546 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2547
Arthur Hung72d8dc32020-03-28 00:48:39 +00002548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08002549
2550 NotifyMotionArgs motionArgs =
2551 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2552 ADISPLAY_ID_DEFAULT);
2553 mDispatcher->notifyMotion(&motionArgs);
2554
2555 InputEvent* event = window->consume();
2556 ASSERT_NE(event, nullptr);
2557
2558 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
2559 ASSERT_NE(verified, nullptr);
2560 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
2561
2562 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
2563 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
2564 EXPECT_EQ(motionArgs.source, verified->source);
2565 EXPECT_EQ(motionArgs.displayId, verified->displayId);
2566
2567 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
2568
2569 EXPECT_EQ(motionArgs.pointerCoords[0].getX(), verifiedMotion.rawX);
2570 EXPECT_EQ(motionArgs.pointerCoords[0].getY(), verifiedMotion.rawY);
2571 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
2572 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
2573 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
2574 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
2575 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
2576}
2577
Prabir Pradhan664834b2021-05-20 16:00:42 -07002578TEST_F(InputDispatcherTest, NonPointerMotionEvent_JoystickAndTouchpadNotTransformed) {
yunho.shinf4a80b82020-11-16 21:13:57 +09002579 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2580 sp<FakeWindowHandle> window =
2581 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2582 const std::string name = window->getName();
2583
2584 // Window gets transformed by offset values.
2585 window->setWindowOffset(500.0f, 500.0f);
2586
2587 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2588 window->setFocusable(true);
2589
2590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2591
2592 // First, we set focused window so that focusedWindowHandle is not null.
2593 setFocusedWindow(window);
2594
2595 // Second, we consume focus event if it is right or wrong according to onFocusChangedLocked.
2596 window->consumeFocusEvent(true);
2597
Prabir Pradhan664834b2021-05-20 16:00:42 -07002598 constexpr const std::array nonTransformedSources = {std::pair(AINPUT_SOURCE_TOUCHPAD,
2599 AMOTION_EVENT_ACTION_DOWN),
2600 std::pair(AINPUT_SOURCE_JOYSTICK,
2601 AMOTION_EVENT_ACTION_MOVE)};
2602 for (const auto& [source, action] : nonTransformedSources) {
2603 const NotifyMotionArgs motionArgs = generateMotionArgs(action, source, ADISPLAY_ID_DEFAULT);
Prabir Pradhanbd527712021-03-09 19:17:09 -08002604 mDispatcher->notifyMotion(&motionArgs);
yunho.shinf4a80b82020-11-16 21:13:57 +09002605
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002606 MotionEvent* event = window->consumeMotion();
Prabir Pradhanbd527712021-03-09 19:17:09 -08002607 ASSERT_NE(event, nullptr);
yunho.shinf4a80b82020-11-16 21:13:57 +09002608
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00002609 const MotionEvent& motionEvent = *event;
Prabir Pradhan664834b2021-05-20 16:00:42 -07002610 EXPECT_EQ(action, motionEvent.getAction());
Prabir Pradhanbd527712021-03-09 19:17:09 -08002611 EXPECT_EQ(motionArgs.pointerCount, motionEvent.getPointerCount());
yunho.shinf4a80b82020-11-16 21:13:57 +09002612
Prabir Pradhanbd527712021-03-09 19:17:09 -08002613 float expectedX = motionArgs.pointerCoords[0].getX();
2614 float expectedY = motionArgs.pointerCoords[0].getY();
yunho.shinf4a80b82020-11-16 21:13:57 +09002615
Prabir Pradhanbd527712021-03-09 19:17:09 -08002616 // Ensure the axis values from the final motion event are not transformed.
2617 EXPECT_EQ(expectedX, motionEvent.getX(0))
2618 << "expected " << expectedX << " for x coord of " << name.c_str() << ", got "
2619 << motionEvent.getX(0);
2620 EXPECT_EQ(expectedY, motionEvent.getY(0))
2621 << "expected " << expectedY << " for y coord of " << name.c_str() << ", got "
2622 << motionEvent.getY(0);
2623 // Ensure the raw and transformed axis values for the motion event are the same.
2624 EXPECT_EQ(motionEvent.getRawX(0), motionEvent.getX(0))
2625 << "expected raw and transformed X-axis values to be equal";
2626 EXPECT_EQ(motionEvent.getRawY(0), motionEvent.getY(0))
2627 << "expected raw and transformed Y-axis values to be equal";
2628 }
yunho.shinf4a80b82020-11-16 21:13:57 +09002629}
2630
chaviw09c8d2d2020-08-24 15:48:26 -07002631/**
2632 * Ensure that separate calls to sign the same data are generating the same key.
2633 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
2634 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
2635 * tests.
2636 */
2637TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
2638 KeyEvent event = getTestKeyEvent();
2639 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2640
2641 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
2642 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
2643 ASSERT_EQ(hmac1, hmac2);
2644}
2645
2646/**
2647 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
2648 */
2649TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
2650 KeyEvent event = getTestKeyEvent();
2651 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
2652 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
2653
2654 verifiedEvent.deviceId += 1;
2655 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2656
2657 verifiedEvent.source += 1;
2658 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2659
2660 verifiedEvent.eventTimeNanos += 1;
2661 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2662
2663 verifiedEvent.displayId += 1;
2664 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2665
2666 verifiedEvent.action += 1;
2667 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2668
2669 verifiedEvent.downTimeNanos += 1;
2670 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2671
2672 verifiedEvent.flags += 1;
2673 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2674
2675 verifiedEvent.keyCode += 1;
2676 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2677
2678 verifiedEvent.scanCode += 1;
2679 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2680
2681 verifiedEvent.metaState += 1;
2682 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2683
2684 verifiedEvent.repeatCount += 1;
2685 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
2686}
2687
Vishnu Nair958da932020-08-21 17:12:37 -07002688TEST_F(InputDispatcherTest, SetFocusedWindow) {
2689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2690 sp<FakeWindowHandle> windowTop =
2691 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2692 sp<FakeWindowHandle> windowSecond =
2693 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2694 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2695
2696 // Top window is also focusable but is not granted focus.
2697 windowTop->setFocusable(true);
2698 windowSecond->setFocusable(true);
2699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2700 setFocusedWindow(windowSecond);
2701
2702 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002703 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2704 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002705
2706 // Focused window should receive event.
2707 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2708 windowTop->assertNoEvents();
2709}
2710
2711TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
2712 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2713 sp<FakeWindowHandle> window =
2714 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2715 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2716
2717 window->setFocusable(true);
2718 // Release channel for window is no longer valid.
2719 window->releaseChannel();
2720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2721 setFocusedWindow(window);
2722
2723 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002724 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2725 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002726
2727 // window channel is invalid, so it should not receive any input event.
2728 window->assertNoEvents();
2729}
2730
2731TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
2732 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2733 sp<FakeWindowHandle> window =
2734 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2735 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2736
2737 // Window is not focusable.
2738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2739 setFocusedWindow(window);
2740
2741 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002742 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2743 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002744
2745 // window is invalid, so it should not receive any input event.
2746 window->assertNoEvents();
2747}
2748
2749TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
2750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2751 sp<FakeWindowHandle> windowTop =
2752 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2753 sp<FakeWindowHandle> windowSecond =
2754 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2755 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2756
2757 windowTop->setFocusable(true);
2758 windowSecond->setFocusable(true);
2759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2760 setFocusedWindow(windowTop);
2761 windowTop->consumeFocusEvent(true);
2762
2763 setFocusedWindow(windowSecond, windowTop);
2764 windowSecond->consumeFocusEvent(true);
2765 windowTop->consumeFocusEvent(false);
2766
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
2768 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07002769
2770 // Focused window should receive event.
2771 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
2772}
2773
2774TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
2775 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2776 sp<FakeWindowHandle> windowTop =
2777 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
2778 sp<FakeWindowHandle> windowSecond =
2779 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2780 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2781
2782 windowTop->setFocusable(true);
2783 windowSecond->setFocusable(true);
2784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
2785 setFocusedWindow(windowSecond, windowTop);
2786
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002787 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
2788 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07002789
2790 // Event should be dropped.
2791 windowTop->assertNoEvents();
2792 windowSecond->assertNoEvents();
2793}
2794
2795TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
2796 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2797 sp<FakeWindowHandle> window =
2798 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
2799 sp<FakeWindowHandle> previousFocusedWindow =
2800 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
2801 ADISPLAY_ID_DEFAULT);
2802 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2803
2804 window->setFocusable(true);
2805 previousFocusedWindow->setFocusable(true);
2806 window->setVisible(false);
2807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
2808 setFocusedWindow(previousFocusedWindow);
2809 previousFocusedWindow->consumeFocusEvent(true);
2810
2811 // Requesting focus on invisible window takes focus from currently focused window.
2812 setFocusedWindow(window);
2813 previousFocusedWindow->consumeFocusEvent(false);
2814
2815 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07002817 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002818 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07002819
2820 // Window does not get focus event or key down.
2821 window->assertNoEvents();
2822
2823 // Window becomes visible.
2824 window->setVisible(true);
2825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2826
2827 // Window receives focus event.
2828 window->consumeFocusEvent(true);
2829 // Focused window receives key down.
2830 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2831}
2832
Vishnu Nair599f1412021-06-21 10:39:58 -07002833TEST_F(InputDispatcherTest, DisplayRemoved) {
2834 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2835 sp<FakeWindowHandle> window =
2836 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
2837 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2838
2839 // window is granted focus.
2840 window->setFocusable(true);
2841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2842 setFocusedWindow(window);
2843 window->consumeFocusEvent(true);
2844
2845 // When a display is removed window loses focus.
2846 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
2847 window->consumeFocusEvent(false);
2848}
2849
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002850/**
2851 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
2852 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
2853 * of the 'slipperyEnterWindow'.
2854 *
2855 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
2856 * a way so that the touched location is no longer covered by the top window.
2857 *
2858 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
2859 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
2860 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
2861 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
2862 * with ACTION_DOWN).
2863 * Thus, the touch has been transferred from the top window into the bottom window, because the top
2864 * window moved itself away from the touched location and had Flag::SLIPPERY.
2865 *
2866 * Even though the top window moved away from the touched location, it is still obscuring the bottom
2867 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
2868 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
2869 *
2870 * In this test, we ensure that the event received by the bottom window has
2871 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
2872 */
2873TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
2874 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
2875 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
2876
2877 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2878 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2879
2880 sp<FakeWindowHandle> slipperyExitWindow =
2881 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05002882 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002883 // Make sure this one overlaps the bottom window
2884 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
2885 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
2886 // one. Windows with the same owner are not considered to be occluding each other.
2887 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
2888
2889 sp<FakeWindowHandle> slipperyEnterWindow =
2890 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2891 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
2892
2893 mDispatcher->setInputWindows(
2894 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2895
2896 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
2897 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2898 ADISPLAY_ID_DEFAULT, {{50, 50}});
2899 mDispatcher->notifyMotion(&args);
2900 slipperyExitWindow->consumeMotionDown();
2901 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
2902 mDispatcher->setInputWindows(
2903 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
2904
2905 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2906 ADISPLAY_ID_DEFAULT, {{51, 51}});
2907 mDispatcher->notifyMotion(&args);
2908
2909 slipperyExitWindow->consumeMotionCancel();
2910
2911 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
2912 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
2913}
2914
Garfield Tan1c7bc862020-01-28 13:24:04 -08002915class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
2916protected:
2917 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
2918 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
2919
Chris Yea209fde2020-07-22 13:54:51 -07002920 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002921 sp<FakeWindowHandle> mWindow;
2922
2923 virtual void SetUp() override {
2924 mFakePolicy = new FakeInputDispatcherPolicy();
2925 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
2926 mDispatcher = new InputDispatcher(mFakePolicy);
2927 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
2928 ASSERT_EQ(OK, mDispatcher->start());
2929
2930 setUpWindow();
2931 }
2932
2933 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07002934 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08002935 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2936
Vishnu Nair47074b82020-08-14 11:54:47 -07002937 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002939 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08002940 mWindow->consumeFocusEvent(true);
2941 }
2942
Chris Ye2ad95392020-09-01 13:44:44 -07002943 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002944 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002945 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002946 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
2947 mDispatcher->notifyKey(&keyArgs);
2948
2949 // Window should receive key down event.
2950 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2951 }
2952
2953 void expectKeyRepeatOnce(int32_t repeatCount) {
2954 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
2955 InputEvent* repeatEvent = mWindow->consume();
2956 ASSERT_NE(nullptr, repeatEvent);
2957
2958 uint32_t eventType = repeatEvent->getType();
2959 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
2960
2961 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
2962 uint32_t eventAction = repeatKeyEvent->getAction();
2963 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
2964 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
2965 }
2966
Chris Ye2ad95392020-09-01 13:44:44 -07002967 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08002968 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07002969 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08002970 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
2971 mDispatcher->notifyKey(&keyArgs);
2972
2973 // Window should receive key down event.
2974 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2975 0 /*expectedFlags*/);
2976 }
2977};
2978
2979TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07002980 sendAndConsumeKeyDown(1 /* deviceId */);
2981 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2982 expectKeyRepeatOnce(repeatCount);
2983 }
2984}
2985
2986TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
2987 sendAndConsumeKeyDown(1 /* deviceId */);
2988 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2989 expectKeyRepeatOnce(repeatCount);
2990 }
2991 sendAndConsumeKeyDown(2 /* deviceId */);
2992 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08002993 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
2994 expectKeyRepeatOnce(repeatCount);
2995 }
2996}
2997
2998TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07002999 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003000 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003001 sendAndConsumeKeyUp(1 /* deviceId */);
3002 mWindow->assertNoEvents();
3003}
3004
3005TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3006 sendAndConsumeKeyDown(1 /* deviceId */);
3007 expectKeyRepeatOnce(1 /*repeatCount*/);
3008 sendAndConsumeKeyDown(2 /* deviceId */);
3009 expectKeyRepeatOnce(1 /*repeatCount*/);
3010 // Stale key up from device 1.
3011 sendAndConsumeKeyUp(1 /* deviceId */);
3012 // Device 2 is still down, keep repeating
3013 expectKeyRepeatOnce(2 /*repeatCount*/);
3014 expectKeyRepeatOnce(3 /*repeatCount*/);
3015 // Device 2 key up
3016 sendAndConsumeKeyUp(2 /* deviceId */);
3017 mWindow->assertNoEvents();
3018}
3019
3020TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3021 sendAndConsumeKeyDown(1 /* deviceId */);
3022 expectKeyRepeatOnce(1 /*repeatCount*/);
3023 sendAndConsumeKeyDown(2 /* deviceId */);
3024 expectKeyRepeatOnce(1 /*repeatCount*/);
3025 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3026 sendAndConsumeKeyUp(2 /* deviceId */);
3027 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003028 mWindow->assertNoEvents();
3029}
3030
liushenxiang42232912021-05-21 20:24:09 +08003031TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3032 sendAndConsumeKeyDown(DEVICE_ID);
3033 expectKeyRepeatOnce(1 /*repeatCount*/);
3034 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3035 mDispatcher->notifyDeviceReset(&args);
3036 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3037 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3038 mWindow->assertNoEvents();
3039}
3040
Garfield Tan1c7bc862020-01-28 13:24:04 -08003041TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003042 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003043 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3044 InputEvent* repeatEvent = mWindow->consume();
3045 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3046 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3047 IdGenerator::getSource(repeatEvent->getId()));
3048 }
3049}
3050
3051TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003052 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003053
3054 std::unordered_set<int32_t> idSet;
3055 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3056 InputEvent* repeatEvent = mWindow->consume();
3057 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3058 int32_t id = repeatEvent->getId();
3059 EXPECT_EQ(idSet.end(), idSet.find(id));
3060 idSet.insert(id);
3061 }
3062}
3063
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003064/* Test InputDispatcher for MultiDisplay */
3065class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3066public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003067 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003068 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003069
Chris Yea209fde2020-07-22 13:54:51 -07003070 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003071 windowInPrimary =
3072 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003073
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003074 // Set focus window for primary display, but focused display would be second one.
3075 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003076 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003077 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003078 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003079 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003080
Chris Yea209fde2020-07-22 13:54:51 -07003081 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003082 windowInSecondary =
3083 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003084 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003085 // Set focus display to second one.
3086 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3087 // Set focus window for second display.
3088 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003089 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003090 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003091 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003093 }
3094
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003095 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003096 InputDispatcherTest::TearDown();
3097
Chris Yea209fde2020-07-22 13:54:51 -07003098 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003099 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003100 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003101 windowInSecondary.clear();
3102 }
3103
3104protected:
Chris Yea209fde2020-07-22 13:54:51 -07003105 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003106 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003107 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003108 sp<FakeWindowHandle> windowInSecondary;
3109};
3110
3111TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3112 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3114 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3115 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003116 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003117 windowInSecondary->assertNoEvents();
3118
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003119 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003120 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3121 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3122 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003123 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003124 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003125}
3126
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003127TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003128 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003129 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3130 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003131 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003132 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003133 windowInSecondary->assertNoEvents();
3134
3135 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003137 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003138 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003139 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003140
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003141 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003142 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003143
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003144 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003145 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3146 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003147
3148 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003149 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003150 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003151 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003152 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003153 windowInSecondary->assertNoEvents();
3154}
3155
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003156// Test per-display input monitors for motion event.
3157TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003158 FakeMonitorReceiver monitorInPrimary =
3159 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3160 FakeMonitorReceiver monitorInSecondary =
3161 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003162
3163 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3165 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3166 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003167 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003168 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003169 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003170 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003171
3172 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3175 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003176 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003177 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003178 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003179 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003180
3181 // Test inject a non-pointer motion event.
3182 // If specific a display, it will dispatch to the focused window of particular display,
3183 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003184 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3185 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3186 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003187 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003188 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003189 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003190 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003191}
3192
3193// Test per-display input monitors for key event.
3194TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003195 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003196 FakeMonitorReceiver monitorInPrimary =
3197 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3198 FakeMonitorReceiver monitorInSecondary =
3199 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003200
3201 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003202 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3203 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003204 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003205 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003206 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003207 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003208}
3209
Vishnu Nair958da932020-08-21 17:12:37 -07003210TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3211 sp<FakeWindowHandle> secondWindowInPrimary =
3212 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3213 secondWindowInPrimary->setFocusable(true);
3214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3215 setFocusedWindow(secondWindowInPrimary);
3216 windowInPrimary->consumeFocusEvent(false);
3217 secondWindowInPrimary->consumeFocusEvent(true);
3218
3219 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003220 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3221 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003222 windowInPrimary->assertNoEvents();
3223 windowInSecondary->assertNoEvents();
3224 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3225}
3226
Jackal Guof9696682018-10-05 12:23:23 +08003227class InputFilterTest : public InputDispatcherTest {
3228protected:
Jackal Guof9696682018-10-05 12:23:23 +08003229 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered) {
3230 NotifyMotionArgs motionArgs;
3231
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003232 motionArgs =
3233 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003234 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003235 motionArgs =
3236 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003237 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003238 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003239 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003240 mFakePolicy->assertFilterInputEventWasCalled(motionArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003241 } else {
3242 mFakePolicy->assertFilterInputEventWasNotCalled();
3243 }
3244 }
3245
3246 void testNotifyKey(bool expectToBeFiltered) {
3247 NotifyKeyArgs keyArgs;
3248
3249 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3250 mDispatcher->notifyKey(&keyArgs);
3251 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3252 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003253 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003254
3255 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003256 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003257 } else {
3258 mFakePolicy->assertFilterInputEventWasNotCalled();
3259 }
3260 }
3261};
3262
3263// Test InputFilter for MotionEvent
3264TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3265 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3266 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3267 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3268
3269 // Enable InputFilter
3270 mDispatcher->setInputFilterEnabled(true);
3271 // Test touch on both primary and second display, and check if both events are filtered.
3272 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3273 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3274
3275 // Disable InputFilter
3276 mDispatcher->setInputFilterEnabled(false);
3277 // Test touch on both primary and second display, and check if both events aren't filtered.
3278 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3279 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3280}
3281
3282// Test InputFilter for KeyEvent
3283TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3284 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3285 testNotifyKey(/*expectToBeFiltered*/ false);
3286
3287 // Enable InputFilter
3288 mDispatcher->setInputFilterEnabled(true);
3289 // Send a key event, and check if it is filtered.
3290 testNotifyKey(/*expectToBeFiltered*/ true);
3291
3292 // Disable InputFilter
3293 mDispatcher->setInputFilterEnabled(false);
3294 // Send a key event, and check if it isn't filtered.
3295 testNotifyKey(/*expectToBeFiltered*/ false);
3296}
3297
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003298class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3299protected:
3300 virtual void SetUp() override {
3301 InputDispatcherTest::SetUp();
3302
3303 /**
3304 * We don't need to enable input filter to test the injected event policy, but we enabled it
3305 * here to make the tests more realistic, since this policy only matters when inputfilter is
3306 * on.
3307 */
3308 mDispatcher->setInputFilterEnabled(true);
3309
3310 std::shared_ptr<InputApplicationHandle> application =
3311 std::make_shared<FakeApplicationHandle>();
3312 mWindow =
3313 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3314
3315 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3316 mWindow->setFocusable(true);
3317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3318 setFocusedWindow(mWindow);
3319 mWindow->consumeFocusEvent(true);
3320 }
3321
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003322 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3323 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003324 KeyEvent event;
3325
3326 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3327 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3328 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3329 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3330 const int32_t additionalPolicyFlags =
3331 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3333 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3334 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3335 policyFlags | additionalPolicyFlags));
3336
3337 InputEvent* received = mWindow->consume();
3338 ASSERT_NE(nullptr, received);
3339 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003340 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3341 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3342 ASSERT_EQ(flags, keyEvent.getFlags());
3343 }
3344
3345 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3346 int32_t flags) {
3347 MotionEvent event;
3348 PointerProperties pointerProperties[1];
3349 PointerCoords pointerCoords[1];
3350 pointerProperties[0].clear();
3351 pointerProperties[0].id = 0;
3352 pointerCoords[0].clear();
3353 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3354 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3355
3356 ui::Transform identityTransform;
3357 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3358 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3359 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3360 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3361 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Evan Rosky09576692021-07-01 12:22:09 -07003362 AMOTION_EVENT_INVALID_CURSOR_POSITION, ui::Transform::ROT_0,
3363 0 /*INVALID_DISPLAY_SIZE*/, 0 /*INVALID_DISPLAY_SIZE*/, eventTime,
3364 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003365 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3366
3367 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3369 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3370 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3371 policyFlags | additionalPolicyFlags));
3372
3373 InputEvent* received = mWindow->consume();
3374 ASSERT_NE(nullptr, received);
3375 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3376 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3377 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3378 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003379 }
3380
3381private:
3382 sp<FakeWindowHandle> mWindow;
3383};
3384
3385TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003386 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3387 // filter. Without it, the event will no different from a regularly injected event, and the
3388 // injected device id will be overwritten.
3389 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3390 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003391}
3392
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003393TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003394 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003395 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3396 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3397}
3398
3399TEST_F(InputFilterInjectionPolicyTest,
3400 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3401 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3402 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3403 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003404}
3405
3406TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3407 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003408 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003409}
3410
chaviwfd6d3512019-03-25 13:23:49 -07003411class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003412 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003413 InputDispatcherTest::SetUp();
3414
Chris Yea209fde2020-07-22 13:54:51 -07003415 std::shared_ptr<FakeApplicationHandle> application =
3416 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003417 mUnfocusedWindow =
3418 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003419 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3420 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3421 // window.
chaviw3277faf2021-05-19 16:45:23 -05003422 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003423
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003424 mFocusedWindow =
3425 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3426 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003427 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003428
3429 // Set focused application.
3430 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003431 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003432
3433 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003435 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003436 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003437 }
3438
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003439 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003440 InputDispatcherTest::TearDown();
3441
3442 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003443 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003444 }
3445
3446protected:
3447 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003448 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003449 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003450};
3451
3452// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3453// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
3454// the onPointerDownOutsideFocus callback.
3455TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003456 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003457 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3458 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003459 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003460 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003461
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003462 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07003463 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
3464}
3465
3466// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
3467// DOWN on the window that doesn't have focus. Ensure no window received the
3468// onPointerDownOutsideFocus callback.
3469TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003471 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003472 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003473 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003474
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003475 ASSERT_TRUE(mDispatcher->waitForIdle());
3476 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003477}
3478
3479// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
3480// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
3481TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3483 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003484 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003485 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003486
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003487 ASSERT_TRUE(mDispatcher->waitForIdle());
3488 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003489}
3490
3491// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
3492// DOWN on the window that already has focus. Ensure no window received the
3493// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003494TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003495 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003496 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003497 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07003499 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07003500
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003501 ASSERT_TRUE(mDispatcher->waitForIdle());
3502 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07003503}
3504
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08003505// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
3506// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
3507TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
3508 const MotionEvent event =
3509 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
3510 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3511 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
3512 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
3513 .build();
3514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
3515 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3516 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
3517
3518 ASSERT_TRUE(mDispatcher->waitForIdle());
3519 mFakePolicy->assertOnPointerDownWasNotCalled();
3520 // Ensure that the unfocused window did not receive any FOCUS events.
3521 mUnfocusedWindow->assertNoEvents();
3522}
3523
chaviwaf87b3e2019-10-01 16:59:28 -07003524// These tests ensures we can send touch events to a single client when there are multiple input
3525// windows that point to the same client token.
3526class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
3527 virtual void SetUp() override {
3528 InputDispatcherTest::SetUp();
3529
Chris Yea209fde2020-07-22 13:54:51 -07003530 std::shared_ptr<FakeApplicationHandle> application =
3531 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07003532 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
3533 ADISPLAY_ID_DEFAULT);
3534 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
3535 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05003536 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003537 mWindow1->setFrame(Rect(0, 0, 100, 100));
3538
3539 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
3540 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05003541 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07003542 mWindow2->setFrame(Rect(100, 100, 200, 200));
3543
Arthur Hung72d8dc32020-03-28 00:48:39 +00003544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07003545 }
3546
3547protected:
3548 sp<FakeWindowHandle> mWindow1;
3549 sp<FakeWindowHandle> mWindow2;
3550
3551 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05003552 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07003553 vec2 vals = windowInfo->transform.transform(point.x, point.y);
3554 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07003555 }
3556
3557 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
3558 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003559 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07003560 InputEvent* event = window->consume();
3561
3562 ASSERT_NE(nullptr, event) << name.c_str()
3563 << ": consumer should have returned non-NULL event.";
3564
3565 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
3566 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
3567 << " event, got " << inputEventTypeToString(event->getType()) << " event";
3568
3569 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
3570 EXPECT_EQ(expectedAction, motionEvent.getAction());
3571
3572 for (size_t i = 0; i < points.size(); i++) {
3573 float expectedX = points[i].x;
3574 float expectedY = points[i].y;
3575
3576 EXPECT_EQ(expectedX, motionEvent.getX(i))
3577 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
3578 << ", got " << motionEvent.getX(i);
3579 EXPECT_EQ(expectedY, motionEvent.getY(i))
3580 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
3581 << ", got " << motionEvent.getY(i);
3582 }
3583 }
chaviw9eaa22c2020-07-01 16:21:27 -07003584
3585 void touchAndAssertPositions(int32_t action, std::vector<PointF> touchedPoints,
3586 std::vector<PointF> expectedPoints) {
3587 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
3588 ADISPLAY_ID_DEFAULT, touchedPoints);
3589 mDispatcher->notifyMotion(&motionArgs);
3590
3591 // Always consume from window1 since it's the window that has the InputReceiver
3592 consumeMotionEvent(mWindow1, action, expectedPoints);
3593 }
chaviwaf87b3e2019-10-01 16:59:28 -07003594};
3595
3596TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
3597 // Touch Window 1
3598 PointF touchedPoint = {10, 10};
3599 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003600 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003601
3602 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003603 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003604
3605 // Touch Window 2
3606 touchedPoint = {150, 150};
3607 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003608 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003609}
3610
chaviw9eaa22c2020-07-01 16:21:27 -07003611TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
3612 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07003613 mWindow2->setWindowScale(0.5f, 0.5f);
3614
3615 // Touch Window 1
3616 PointF touchedPoint = {10, 10};
3617 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003618 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003619 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07003620 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003621
3622 // Touch Window 2
3623 touchedPoint = {150, 150};
3624 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07003625 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
3626 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003627
chaviw9eaa22c2020-07-01 16:21:27 -07003628 // Update the transform so rotation is set
3629 mWindow2->setWindowTransform(0, -1, 1, 0);
3630 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
3631 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07003632}
3633
chaviw9eaa22c2020-07-01 16:21:27 -07003634TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003635 mWindow2->setWindowScale(0.5f, 0.5f);
3636
3637 // Touch Window 1
3638 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3639 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003640 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003641
3642 // Touch Window 2
3643 int32_t actionPointerDown =
3644 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003645 touchedPoints.push_back(PointF{150, 150});
3646 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3647 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003648
chaviw9eaa22c2020-07-01 16:21:27 -07003649 // Release Window 2
3650 int32_t actionPointerUp =
3651 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3652 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3653 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003654
chaviw9eaa22c2020-07-01 16:21:27 -07003655 // Update the transform so rotation is set for Window 2
3656 mWindow2->setWindowTransform(0, -1, 1, 0);
3657 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3658 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003659}
3660
chaviw9eaa22c2020-07-01 16:21:27 -07003661TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003662 mWindow2->setWindowScale(0.5f, 0.5f);
3663
3664 // Touch Window 1
3665 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3666 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003667 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003668
3669 // Touch Window 2
3670 int32_t actionPointerDown =
3671 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003672 touchedPoints.push_back(PointF{150, 150});
3673 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003674
chaviw9eaa22c2020-07-01 16:21:27 -07003675 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003676
3677 // Move both windows
3678 touchedPoints = {{20, 20}, {175, 175}};
3679 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3680 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3681
chaviw9eaa22c2020-07-01 16:21:27 -07003682 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003683
chaviw9eaa22c2020-07-01 16:21:27 -07003684 // Release Window 2
3685 int32_t actionPointerUp =
3686 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3687 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
3688 expectedPoints.pop_back();
3689
3690 // Touch Window 2
3691 mWindow2->setWindowTransform(0, -1, 1, 0);
3692 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
3693 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
3694
3695 // Move both windows
3696 touchedPoints = {{20, 20}, {175, 175}};
3697 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3698 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3699
3700 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003701}
3702
3703TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
3704 mWindow1->setWindowScale(0.5f, 0.5f);
3705
3706 // Touch Window 1
3707 std::vector<PointF> touchedPoints = {PointF{10, 10}};
3708 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07003709 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003710
3711 // Touch Window 2
3712 int32_t actionPointerDown =
3713 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07003714 touchedPoints.push_back(PointF{150, 150});
3715 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003716
chaviw9eaa22c2020-07-01 16:21:27 -07003717 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003718
3719 // Move both windows
3720 touchedPoints = {{20, 20}, {175, 175}};
3721 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
3722 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
3723
chaviw9eaa22c2020-07-01 16:21:27 -07003724 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00003725}
3726
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003727class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
3728 virtual void SetUp() override {
3729 InputDispatcherTest::SetUp();
3730
Chris Yea209fde2020-07-22 13:54:51 -07003731 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003732 mApplication->setDispatchingTimeout(20ms);
3733 mWindow =
3734 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3735 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05003736 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07003737 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003738 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3739 // window.
chaviw3277faf2021-05-19 16:45:23 -05003740 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003741
3742 // Set focused application.
3743 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
3744
3745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003746 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003747 mWindow->consumeFocusEvent(true);
3748 }
3749
3750 virtual void TearDown() override {
3751 InputDispatcherTest::TearDown();
3752 mWindow.clear();
3753 }
3754
3755protected:
Chris Yea209fde2020-07-22 13:54:51 -07003756 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003757 sp<FakeWindowHandle> mWindow;
3758 static constexpr PointF WINDOW_LOCATION = {20, 20};
3759
3760 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003761 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003762 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3763 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003765 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3766 WINDOW_LOCATION));
3767 }
3768};
3769
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003770// Send a tap and respond, which should not cause an ANR.
3771TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
3772 tapOnWindow();
3773 mWindow->consumeMotionDown();
3774 mWindow->consumeMotionUp();
3775 ASSERT_TRUE(mDispatcher->waitForIdle());
3776 mFakePolicy->assertNotifyAnrWasNotCalled();
3777}
3778
3779// Send a regular key and respond, which should not cause an ANR.
3780TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003782 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
3783 ASSERT_TRUE(mDispatcher->waitForIdle());
3784 mFakePolicy->assertNotifyAnrWasNotCalled();
3785}
3786
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003787TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
3788 mWindow->setFocusable(false);
3789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3790 mWindow->consumeFocusEvent(false);
3791
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003792 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003793 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003794 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
3795 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05003797 // Key will not go to window because we have no focused window.
3798 // The 'no focused window' ANR timer should start instead.
3799
3800 // Now, the focused application goes away.
3801 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
3802 // The key should get dropped and there should be no ANR.
3803
3804 ASSERT_TRUE(mDispatcher->waitForIdle());
3805 mFakePolicy->assertNotifyAnrWasNotCalled();
3806}
3807
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003808// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003809// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
3810// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003811TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003813 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3814 WINDOW_LOCATION));
3815
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003816 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
3817 ASSERT_TRUE(sequenceNum);
3818 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003819 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003820
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003821 mWindow->finishEvent(*sequenceNum);
3822 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3823 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003824 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003825 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003826}
3827
3828// Send a key to the app and have the app not respond right away.
3829TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
3830 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003832 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
3833 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003834 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003835 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07003836 ASSERT_TRUE(mDispatcher->waitForIdle());
3837}
3838
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003839// We have a focused application, but no focused window
3840TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003841 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3843 mWindow->consumeFocusEvent(false);
3844
3845 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003847 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3848 WINDOW_LOCATION));
3849 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
3850 mDispatcher->waitForIdle();
3851 mFakePolicy->assertNotifyAnrWasNotCalled();
3852
3853 // Once a focused event arrives, we get an ANR for this application
3854 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3855 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003856 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003857 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003858 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003859 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003860 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003861 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003862 ASSERT_TRUE(mDispatcher->waitForIdle());
3863}
3864
3865// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003866// Make sure that we don't notify policy twice about the same ANR.
3867TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003868 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3870 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003871
3872 // Once a focused event arrives, we get an ANR for this application
3873 // We specify the injection timeout to be smaller than the application timeout, to ensure that
3874 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003875 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003876 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003877 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003878 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003879 const std::chrono::duration appTimeout =
3880 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003881 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003882
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003883 std::this_thread::sleep_for(appTimeout);
3884 // ANR should not be raised again. It is up to policy to do that if it desires.
3885 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003886
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003887 // If we now get a focused window, the ANR should stop, but the policy handles that via
3888 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003889 ASSERT_TRUE(mDispatcher->waitForIdle());
3890}
3891
3892// We have a focused application, but no focused window
3893TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07003894 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3896 mWindow->consumeFocusEvent(false);
3897
3898 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003899 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003900 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003901 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
3902 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003903
3904 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05003905 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003906
3907 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003908 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003909 ASSERT_TRUE(mDispatcher->waitForIdle());
3910 mWindow->assertNoEvents();
3911}
3912
3913/**
3914 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
3915 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
3916 * If we process 1 of the events, but ANR on the second event with the same timestamp,
3917 * the ANR mechanism should still work.
3918 *
3919 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
3920 * DOWN event, while not responding on the second one.
3921 */
3922TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
3923 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
3924 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3925 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3926 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3927 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003928 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003929
3930 // Now send ACTION_UP, with identical timestamp
3931 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3932 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
3933 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
3934 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003935 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003936
3937 // We have now sent down and up. Let's consume first event and then ANR on the second.
3938 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3939 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003940 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003941}
3942
3943// If an app is not responding to a key event, gesture monitors should continue to receive
3944// new motion events
3945TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
3946 FakeMonitorReceiver monitor =
3947 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3948 true /*isGestureMonitor*/);
3949
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3951 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003952 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003954
3955 // Stuck on the ACTION_UP
3956 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003957 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003958
3959 // New tap will go to the gesture monitor, but not to the window
3960 tapOnWindow();
3961 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3962 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3963
3964 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3965 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003966 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003967 mWindow->assertNoEvents();
3968 monitor.assertNoEvents();
3969}
3970
3971// If an app is not responding to a motion event, gesture monitors should continue to receive
3972// new motion events
3973TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
3974 FakeMonitorReceiver monitor =
3975 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
3976 true /*isGestureMonitor*/);
3977
3978 tapOnWindow();
3979 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3980 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3981
3982 mWindow->consumeMotionDown();
3983 // Stuck on the ACTION_UP
3984 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003985 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003986
3987 // New tap will go to the gesture monitor, but not to the window
3988 tapOnWindow();
3989 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3990 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
3991
3992 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
3993 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00003994 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003995 mWindow->assertNoEvents();
3996 monitor.assertNoEvents();
3997}
3998
3999// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4000// process events, you don't get an anr. When the window later becomes unresponsive again, you
4001// get an ANR again.
4002// 1. tap -> block on ACTION_UP -> receive ANR
4003// 2. consume all pending events (= queue becomes healthy again)
4004// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4005TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4006 tapOnWindow();
4007
4008 mWindow->consumeMotionDown();
4009 // Block on ACTION_UP
4010 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004011 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004012 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4013 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004014 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004015 mWindow->assertNoEvents();
4016
4017 tapOnWindow();
4018 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004019 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004020 mWindow->consumeMotionUp();
4021
4022 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004023 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004024 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004025 mWindow->assertNoEvents();
4026}
4027
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004028// If a connection remains unresponsive for a while, make sure policy is only notified once about
4029// it.
4030TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004032 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4033 WINDOW_LOCATION));
4034
4035 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004036 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004037 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004038 // 'notifyConnectionUnresponsive' should only be called once per connection
4039 mFakePolicy->assertNotifyAnrWasNotCalled();
4040 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004041 mWindow->consumeMotionDown();
4042 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4043 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4044 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004045 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004046 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004047 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004048}
4049
4050/**
4051 * If a window is processing a motion event, and then a key event comes in, the key event should
4052 * not to to the focused window until the motion is processed.
4053 *
4054 * Warning!!!
4055 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4056 * and the injection timeout that we specify when injecting the key.
4057 * We must have the injection timeout (10ms) be smaller than
4058 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4059 *
4060 * If that value changes, this test should also change.
4061 */
4062TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4063 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4064 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4065
4066 tapOnWindow();
4067 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4068 ASSERT_TRUE(downSequenceNum);
4069 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4070 ASSERT_TRUE(upSequenceNum);
4071 // Don't finish the events yet, and send a key
4072 // Injection will "succeed" because we will eventually give up and send the key to the focused
4073 // window even if motions are still being processed. But because the injection timeout is short,
4074 // we will receive INJECTION_TIMED_OUT as the result.
4075
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004076 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004077 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004078 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4079 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004080 // Key will not be sent to the window, yet, because the window is still processing events
4081 // and the key remains pending, waiting for the touch events to be processed
4082 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4083 ASSERT_FALSE(keySequenceNum);
4084
4085 std::this_thread::sleep_for(500ms);
4086 // if we wait long enough though, dispatcher will give up, and still send the key
4087 // to the focused window, even though we have not yet finished the motion event
4088 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4089 mWindow->finishEvent(*downSequenceNum);
4090 mWindow->finishEvent(*upSequenceNum);
4091}
4092
4093/**
4094 * If a window is processing a motion event, and then a key event comes in, the key event should
4095 * not go to the focused window until the motion is processed.
4096 * If then a new motion comes in, then the pending key event should be going to the currently
4097 * focused window right away.
4098 */
4099TEST_F(InputDispatcherSingleWindowAnr,
4100 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4101 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4103
4104 tapOnWindow();
4105 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4106 ASSERT_TRUE(downSequenceNum);
4107 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4108 ASSERT_TRUE(upSequenceNum);
4109 // Don't finish the events yet, and send a key
4110 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004112 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004113 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004114 // At this point, key is still pending, and should not be sent to the application yet.
4115 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4116 ASSERT_FALSE(keySequenceNum);
4117
4118 // Now tap down again. It should cause the pending key to go to the focused window right away.
4119 tapOnWindow();
4120 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4121 // the other events yet. We can finish events in any order.
4122 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4123 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4124 mWindow->consumeMotionDown();
4125 mWindow->consumeMotionUp();
4126 mWindow->assertNoEvents();
4127}
4128
4129class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4130 virtual void SetUp() override {
4131 InputDispatcherTest::SetUp();
4132
Chris Yea209fde2020-07-22 13:54:51 -07004133 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004134 mApplication->setDispatchingTimeout(10ms);
4135 mUnfocusedWindow =
4136 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4137 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4138 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4139 // window.
4140 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004141 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4142 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4143 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004144
4145 mFocusedWindow =
4146 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004147 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004148 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004149 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004150
4151 // Set focused application.
4152 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004153 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004154
4155 // Expect one focus window exist in display.
4156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004157 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004158 mFocusedWindow->consumeFocusEvent(true);
4159 }
4160
4161 virtual void TearDown() override {
4162 InputDispatcherTest::TearDown();
4163
4164 mUnfocusedWindow.clear();
4165 mFocusedWindow.clear();
4166 }
4167
4168protected:
Chris Yea209fde2020-07-22 13:54:51 -07004169 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004170 sp<FakeWindowHandle> mUnfocusedWindow;
4171 sp<FakeWindowHandle> mFocusedWindow;
4172 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4173 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4174 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4175
4176 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4177
4178 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4179
4180private:
4181 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004182 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004183 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4184 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004186 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4187 location));
4188 }
4189};
4190
4191// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4192// should be ANR'd first.
4193TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004195 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4196 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004198 mFocusedWindow->consumeMotionDown();
4199 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4200 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4201 // We consumed all events, so no ANR
4202 ASSERT_TRUE(mDispatcher->waitForIdle());
4203 mFakePolicy->assertNotifyAnrWasNotCalled();
4204
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004206 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4207 FOCUSED_WINDOW_LOCATION));
4208 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4209 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004210
4211 const std::chrono::duration timeout =
4212 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004213 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004214 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4215 // sequence to make it consistent
4216 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004217 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004218 mFocusedWindow->consumeMotionDown();
4219 // This cancel is generated because the connection was unresponsive
4220 mFocusedWindow->consumeMotionCancel();
4221 mFocusedWindow->assertNoEvents();
4222 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004223 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004224 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004225 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004226}
4227
4228// If we have 2 windows with identical timeouts that are both unresponsive,
4229// it doesn't matter which order they should have ANR.
4230// But we should receive ANR for both.
4231TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4232 // Set the timeout for unfocused window to match the focused window
4233 mUnfocusedWindow->setDispatchingTimeout(10ms);
4234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4235
4236 tapOnFocusedWindow();
4237 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004238 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4239 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004240
4241 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004242 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4243 mFocusedWindow->getToken() == anrConnectionToken2);
4244 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4245 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004246
4247 ASSERT_TRUE(mDispatcher->waitForIdle());
4248 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004249
4250 mFocusedWindow->consumeMotionDown();
4251 mFocusedWindow->consumeMotionUp();
4252 mUnfocusedWindow->consumeMotionOutside();
4253
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004254 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4255 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004256
4257 // Both applications should be marked as responsive, in any order
4258 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4259 mFocusedWindow->getToken() == responsiveToken2);
4260 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4261 mUnfocusedWindow->getToken() == responsiveToken2);
4262 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004263}
4264
4265// If a window is already not responding, the second tap on the same window should be ignored.
4266// We should also log an error to account for the dropped event (not tested here).
4267// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4268TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4269 tapOnFocusedWindow();
4270 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4271 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4272 // Receive the events, but don't respond
4273 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4274 ASSERT_TRUE(downEventSequenceNum);
4275 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4276 ASSERT_TRUE(upEventSequenceNum);
4277 const std::chrono::duration timeout =
4278 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004279 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004280
4281 // Tap once again
4282 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004283 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004284 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4285 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004286 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004287 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4288 FOCUSED_WINDOW_LOCATION));
4289 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4290 // valid touch target
4291 mUnfocusedWindow->assertNoEvents();
4292
4293 // Consume the first tap
4294 mFocusedWindow->finishEvent(*downEventSequenceNum);
4295 mFocusedWindow->finishEvent(*upEventSequenceNum);
4296 ASSERT_TRUE(mDispatcher->waitForIdle());
4297 // The second tap did not go to the focused window
4298 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004299 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004300 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004301 mFakePolicy->assertNotifyAnrWasNotCalled();
4302}
4303
4304// If you tap outside of all windows, there will not be ANR
4305TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004306 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004307 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4308 LOCATION_OUTSIDE_ALL_WINDOWS));
4309 ASSERT_TRUE(mDispatcher->waitForIdle());
4310 mFakePolicy->assertNotifyAnrWasNotCalled();
4311}
4312
4313// Since the focused window is paused, tapping on it should not produce any events
4314TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4315 mFocusedWindow->setPaused(true);
4316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4317
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004318 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004319 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4320 FOCUSED_WINDOW_LOCATION));
4321
4322 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4323 ASSERT_TRUE(mDispatcher->waitForIdle());
4324 // Should not ANR because the window is paused, and touches shouldn't go to it
4325 mFakePolicy->assertNotifyAnrWasNotCalled();
4326
4327 mFocusedWindow->assertNoEvents();
4328 mUnfocusedWindow->assertNoEvents();
4329}
4330
4331/**
4332 * If a window is processing a motion event, and then a key event comes in, the key event should
4333 * not to to the focused window until the motion is processed.
4334 * If a different window becomes focused at this time, the key should go to that window instead.
4335 *
4336 * Warning!!!
4337 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4338 * and the injection timeout that we specify when injecting the key.
4339 * We must have the injection timeout (10ms) be smaller than
4340 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4341 *
4342 * If that value changes, this test should also change.
4343 */
4344TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4345 // Set a long ANR timeout to prevent it from triggering
4346 mFocusedWindow->setDispatchingTimeout(2s);
4347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4348
4349 tapOnUnfocusedWindow();
4350 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4351 ASSERT_TRUE(downSequenceNum);
4352 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4353 ASSERT_TRUE(upSequenceNum);
4354 // Don't finish the events yet, and send a key
4355 // Injection will succeed because we will eventually give up and send the key to the focused
4356 // window even if motions are still being processed.
4357
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004359 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004360 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004362 // Key will not be sent to the window, yet, because the window is still processing events
4363 // and the key remains pending, waiting for the touch events to be processed
4364 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4365 ASSERT_FALSE(keySequenceNum);
4366
4367 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004368 mFocusedWindow->setFocusable(false);
4369 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004371 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004372
4373 // Focus events should precede the key events
4374 mUnfocusedWindow->consumeFocusEvent(true);
4375 mFocusedWindow->consumeFocusEvent(false);
4376
4377 // Finish the tap events, which should unblock dispatcher
4378 mUnfocusedWindow->finishEvent(*downSequenceNum);
4379 mUnfocusedWindow->finishEvent(*upSequenceNum);
4380
4381 // Now that all queues are cleared and no backlog in the connections, the key event
4382 // can finally go to the newly focused "mUnfocusedWindow".
4383 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4384 mFocusedWindow->assertNoEvents();
4385 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004386 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004387}
4388
4389// When the touch stream is split across 2 windows, and one of them does not respond,
4390// then ANR should be raised and the touch should be canceled for the unresponsive window.
4391// The other window should not be affected by that.
4392TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4393 // Touch Window 1
4394 NotifyMotionArgs motionArgs =
4395 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4396 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4397 mDispatcher->notifyMotion(&motionArgs);
4398 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4399 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4400
4401 // Touch Window 2
4402 int32_t actionPointerDown =
4403 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4404
4405 motionArgs =
4406 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4407 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4408 mDispatcher->notifyMotion(&motionArgs);
4409
4410 const std::chrono::duration timeout =
4411 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004412 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004413
4414 mUnfocusedWindow->consumeMotionDown();
4415 mFocusedWindow->consumeMotionDown();
4416 // Focused window may or may not receive ACTION_MOVE
4417 // But it should definitely receive ACTION_CANCEL due to the ANR
4418 InputEvent* event;
4419 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
4420 ASSERT_TRUE(moveOrCancelSequenceNum);
4421 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
4422 ASSERT_NE(nullptr, event);
4423 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
4424 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
4425 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
4426 mFocusedWindow->consumeMotionCancel();
4427 } else {
4428 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
4429 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004431 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004432
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 mUnfocusedWindow->assertNoEvents();
4434 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004435 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436}
4437
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004438/**
4439 * If we have no focused window, and a key comes in, we start the ANR timer.
4440 * The focused application should add a focused window before the timer runs out to prevent ANR.
4441 *
4442 * If the user touches another application during this time, the key should be dropped.
4443 * Next, if a new focused window comes in, without toggling the focused application,
4444 * then no ANR should occur.
4445 *
4446 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
4447 * but in some cases the policy may not update the focused application.
4448 */
4449TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
4450 std::shared_ptr<FakeApplicationHandle> focusedApplication =
4451 std::make_shared<FakeApplicationHandle>();
4452 focusedApplication->setDispatchingTimeout(60ms);
4453 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
4454 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
4455 mFocusedWindow->setFocusable(false);
4456
4457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4458 mFocusedWindow->consumeFocusEvent(false);
4459
4460 // Send a key. The ANR timer should start because there is no focused window.
4461 // 'focusedApplication' will get blamed if this timer completes.
4462 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004463 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004464 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004465 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4466 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05004468
4469 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
4470 // then the injected touches won't cause the focused event to get dropped.
4471 // The dispatcher only checks for whether the queue should be pruned upon queueing.
4472 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
4473 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
4474 // For this test, it means that the key would get delivered to the window once it becomes
4475 // focused.
4476 std::this_thread::sleep_for(10ms);
4477
4478 // Touch unfocused window. This should force the pending key to get dropped.
4479 NotifyMotionArgs motionArgs =
4480 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4481 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
4482 mDispatcher->notifyMotion(&motionArgs);
4483
4484 // We do not consume the motion right away, because that would require dispatcher to first
4485 // process (== drop) the key event, and by that time, ANR will be raised.
4486 // Set the focused window first.
4487 mFocusedWindow->setFocusable(true);
4488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4489 setFocusedWindow(mFocusedWindow);
4490 mFocusedWindow->consumeFocusEvent(true);
4491 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
4492 // to another application. This could be a bug / behaviour in the policy.
4493
4494 mUnfocusedWindow->consumeMotionDown();
4495
4496 ASSERT_TRUE(mDispatcher->waitForIdle());
4497 // Should not ANR because we actually have a focused window. It was just added too slowly.
4498 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
4499}
4500
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004501// These tests ensure we cannot send touch events to a window that's positioned behind a window
4502// that has feature NO_INPUT_CHANNEL.
4503// Layout:
4504// Top (closest to user)
4505// mNoInputWindow (above all windows)
4506// mBottomWindow
4507// Bottom (furthest from user)
4508class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
4509 virtual void SetUp() override {
4510 InputDispatcherTest::SetUp();
4511
4512 mApplication = std::make_shared<FakeApplicationHandle>();
4513 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4514 "Window without input channel", ADISPLAY_ID_DEFAULT,
4515 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
4516
chaviw3277faf2021-05-19 16:45:23 -05004517 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004518 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4519 // It's perfectly valid for this window to not have an associated input channel
4520
4521 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
4522 ADISPLAY_ID_DEFAULT);
4523 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
4524
4525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4526 }
4527
4528protected:
4529 std::shared_ptr<FakeApplicationHandle> mApplication;
4530 sp<FakeWindowHandle> mNoInputWindow;
4531 sp<FakeWindowHandle> mBottomWindow;
4532};
4533
4534TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
4535 PointF touchedPoint = {10, 10};
4536
4537 NotifyMotionArgs motionArgs =
4538 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4539 ADISPLAY_ID_DEFAULT, {touchedPoint});
4540 mDispatcher->notifyMotion(&motionArgs);
4541
4542 mNoInputWindow->assertNoEvents();
4543 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
4544 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
4545 // and therefore should prevent mBottomWindow from receiving touches
4546 mBottomWindow->assertNoEvents();
4547}
4548
4549/**
4550 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
4551 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
4552 */
4553TEST_F(InputDispatcherMultiWindowOcclusionTests,
4554 NoInputChannelFeature_DropsTouchesWithValidChannel) {
4555 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
4556 "Window with input channel and NO_INPUT_CHANNEL",
4557 ADISPLAY_ID_DEFAULT);
4558
chaviw3277faf2021-05-19 16:45:23 -05004559 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05004560 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
4561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
4562
4563 PointF touchedPoint = {10, 10};
4564
4565 NotifyMotionArgs motionArgs =
4566 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4567 ADISPLAY_ID_DEFAULT, {touchedPoint});
4568 mDispatcher->notifyMotion(&motionArgs);
4569
4570 mNoInputWindow->assertNoEvents();
4571 mBottomWindow->assertNoEvents();
4572}
4573
Vishnu Nair958da932020-08-21 17:12:37 -07004574class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
4575protected:
4576 std::shared_ptr<FakeApplicationHandle> mApp;
4577 sp<FakeWindowHandle> mWindow;
4578 sp<FakeWindowHandle> mMirror;
4579
4580 virtual void SetUp() override {
4581 InputDispatcherTest::SetUp();
4582 mApp = std::make_shared<FakeApplicationHandle>();
4583 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4584 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
4585 mWindow->getToken());
4586 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4587 mWindow->setFocusable(true);
4588 mMirror->setFocusable(true);
4589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4590 }
4591};
4592
4593TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
4594 // Request focus on a mirrored window
4595 setFocusedWindow(mMirror);
4596
4597 // window gets focused
4598 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4600 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004601 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4602}
4603
4604// A focused & mirrored window remains focused only if the window and its mirror are both
4605// focusable.
4606TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
4607 setFocusedWindow(mMirror);
4608
4609 // window gets focused
4610 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4612 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004613 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4615 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004616 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4617
4618 mMirror->setFocusable(false);
4619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4620
4621 // window loses focus since one of the windows associated with the token in not focusable
4622 mWindow->consumeFocusEvent(false);
4623
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004624 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4625 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004626 mWindow->assertNoEvents();
4627}
4628
4629// A focused & mirrored window remains focused until the window and its mirror both become
4630// invisible.
4631TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
4632 setFocusedWindow(mMirror);
4633
4634 // window gets focused
4635 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4637 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004638 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4640 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004641 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4642
4643 mMirror->setVisible(false);
4644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4645
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4647 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004648 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4650 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004651 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4652
4653 mWindow->setVisible(false);
4654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4655
4656 // window loses focus only after all windows associated with the token become invisible.
4657 mWindow->consumeFocusEvent(false);
4658
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4660 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004661 mWindow->assertNoEvents();
4662}
4663
4664// A focused & mirrored window remains focused until both windows are removed.
4665TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
4666 setFocusedWindow(mMirror);
4667
4668 // window gets focused
4669 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4671 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004672 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4674 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004675 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4676
4677 // single window is removed but the window token remains focused
4678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
4679
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4681 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004682 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
4684 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004685 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
4686
4687 // Both windows are removed
4688 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
4689 mWindow->consumeFocusEvent(false);
4690
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
4692 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07004693 mWindow->assertNoEvents();
4694}
4695
4696// Focus request can be pending until one window becomes visible.
4697TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
4698 // Request focus on an invisible mirror.
4699 mWindow->setVisible(false);
4700 mMirror->setVisible(false);
4701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4702 setFocusedWindow(mMirror);
4703
4704 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004705 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07004706 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004707 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07004708
4709 mMirror->setVisible(true);
4710 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
4711
4712 // window gets focused
4713 mWindow->consumeFocusEvent(true);
4714 // window gets the pending key event
4715 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4716}
Prabir Pradhan99987712020-11-10 18:43:05 -08004717
4718class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
4719protected:
4720 std::shared_ptr<FakeApplicationHandle> mApp;
4721 sp<FakeWindowHandle> mWindow;
4722 sp<FakeWindowHandle> mSecondWindow;
4723
4724 void SetUp() override {
4725 InputDispatcherTest::SetUp();
4726 mApp = std::make_shared<FakeApplicationHandle>();
4727 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4728 mWindow->setFocusable(true);
4729 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
4730 mSecondWindow->setFocusable(true);
4731
4732 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
4733 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
4734
4735 setFocusedWindow(mWindow);
4736 mWindow->consumeFocusEvent(true);
4737 }
4738
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004739 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
4740 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004741 mDispatcher->notifyPointerCaptureChanged(&args);
4742 }
4743
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004744 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
4745 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08004746 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004747 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
4748 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004749 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004750 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08004751 }
4752};
4753
4754TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
4755 // Ensure that capture cannot be obtained for unfocused windows.
4756 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
4757 mFakePolicy->assertSetPointerCaptureNotCalled();
4758 mSecondWindow->assertNoEvents();
4759
4760 // Ensure that capture can be enabled from the focus window.
4761 requestAndVerifyPointerCapture(mWindow, true);
4762
4763 // Ensure that capture cannot be disabled from a window that does not have capture.
4764 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
4765 mFakePolicy->assertSetPointerCaptureNotCalled();
4766
4767 // Ensure that capture can be disabled from the window with capture.
4768 requestAndVerifyPointerCapture(mWindow, false);
4769}
4770
4771TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004772 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08004773
4774 setFocusedWindow(mSecondWindow);
4775
4776 // Ensure that the capture disabled event was sent first.
4777 mWindow->consumeCaptureEvent(false);
4778 mWindow->consumeFocusEvent(false);
4779 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004780 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004781
4782 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004783 notifyPointerCaptureChanged({});
4784 notifyPointerCaptureChanged(request);
4785 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08004786 mWindow->assertNoEvents();
4787 mSecondWindow->assertNoEvents();
4788 mFakePolicy->assertSetPointerCaptureNotCalled();
4789}
4790
4791TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004792 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08004793
4794 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004795 notifyPointerCaptureChanged({});
4796 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08004797
4798 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004799 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08004800 mWindow->consumeCaptureEvent(false);
4801 mWindow->assertNoEvents();
4802}
4803
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004804TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
4805 requestAndVerifyPointerCapture(mWindow, true);
4806
4807 // The first window loses focus.
4808 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004809 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004810 mWindow->consumeCaptureEvent(false);
4811
4812 // Request Pointer Capture from the second window before the notification from InputReader
4813 // arrives.
4814 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004815 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004816
4817 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004818 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004819
4820 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004821 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08004822
4823 mSecondWindow->consumeFocusEvent(true);
4824 mSecondWindow->consumeCaptureEvent(true);
4825}
4826
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00004827TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
4828 // App repeatedly enables and disables capture.
4829 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4830 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4831 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
4832 mFakePolicy->assertSetPointerCaptureCalled(false);
4833 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
4834 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
4835
4836 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
4837 // first request is now stale, this should do nothing.
4838 notifyPointerCaptureChanged(firstRequest);
4839 mWindow->assertNoEvents();
4840
4841 // InputReader notifies that the second request was enabled.
4842 notifyPointerCaptureChanged(secondRequest);
4843 mWindow->consumeCaptureEvent(true);
4844}
4845
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004846class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
4847protected:
4848 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00004849
4850 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
4851 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
4852
4853 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
4854 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4855
4856 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
4857 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
4858 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
4859 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
4860 MAXIMUM_OBSCURING_OPACITY);
4861
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004862 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004863 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004864 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004865
4866 sp<FakeWindowHandle> mTouchWindow;
4867
4868 virtual void SetUp() override {
4869 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004870 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004871 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
4872 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
4873 }
4874
4875 virtual void TearDown() override {
4876 InputDispatcherTest::TearDown();
4877 mTouchWindow.clear();
4878 }
4879
chaviw3277faf2021-05-19 16:45:23 -05004880 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
4881 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004882 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05004883 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004884 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004885 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004886 return window;
4887 }
4888
4889 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
4890 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
4891 sp<FakeWindowHandle> window =
4892 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
4893 // Generate an arbitrary PID based on the UID
4894 window->setOwnerInfo(1777 + (uid % 10000), uid);
4895 return window;
4896 }
4897
4898 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
4899 NotifyMotionArgs args =
4900 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4901 ADISPLAY_ID_DEFAULT, points);
4902 mDispatcher->notifyMotion(&args);
4903 }
4904};
4905
4906TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004907 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004908 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004910
4911 touch();
4912
4913 mTouchWindow->assertNoEvents();
4914}
4915
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004916TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00004917 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
4918 const sp<FakeWindowHandle>& w =
4919 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
4920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4921
4922 touch();
4923
4924 mTouchWindow->assertNoEvents();
4925}
4926
4927TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004928 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
4929 const sp<FakeWindowHandle>& w =
4930 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
4931 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4932
4933 touch();
4934
4935 w->assertNoEvents();
4936}
4937
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004938TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004939 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
4940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004941
4942 touch();
4943
4944 mTouchWindow->consumeAnyMotionDown();
4945}
4946
4947TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004948 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004949 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004950 w->setFrame(Rect(0, 0, 50, 50));
4951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004952
4953 touch({PointF{100, 100}});
4954
4955 mTouchWindow->consumeAnyMotionDown();
4956}
4957
4958TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004959 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00004960 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00004961 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4962
4963 touch();
4964
4965 mTouchWindow->consumeAnyMotionDown();
4966}
4967
4968TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
4969 const sp<FakeWindowHandle>& w =
4970 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00004972
4973 touch();
4974
4975 mTouchWindow->consumeAnyMotionDown();
4976}
4977
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004978TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
4979 const sp<FakeWindowHandle>& w =
4980 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
4981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4982
4983 touch();
4984
4985 w->assertNoEvents();
4986}
4987
4988/**
4989 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
4990 * inside) while letting them pass-through. Note that even though touch passes through the occluding
4991 * window, the occluding window will still receive ACTION_OUTSIDE event.
4992 */
4993TEST_F(InputDispatcherUntrustedTouchesTest,
4994 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
4995 const sp<FakeWindowHandle>& w =
4996 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05004997 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00004998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
4999
5000 touch();
5001
5002 w->consumeMotionOutside();
5003}
5004
5005TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5006 const sp<FakeWindowHandle>& w =
5007 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005008 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5010
5011 touch();
5012
5013 InputEvent* event = w->consume();
5014 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5015 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5016 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5017 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5018}
5019
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005020TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005021 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005022 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5023 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5025
5026 touch();
5027
5028 mTouchWindow->consumeAnyMotionDown();
5029}
5030
5031TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5032 const sp<FakeWindowHandle>& w =
5033 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5034 MAXIMUM_OBSCURING_OPACITY);
5035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005036
5037 touch();
5038
5039 mTouchWindow->consumeAnyMotionDown();
5040}
5041
5042TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005043 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005044 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5045 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5047
5048 touch();
5049
5050 mTouchWindow->assertNoEvents();
5051}
5052
5053TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5054 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5055 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005056 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5057 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005058 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005059 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5060 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5062
5063 touch();
5064
5065 mTouchWindow->assertNoEvents();
5066}
5067
5068TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5069 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5070 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005071 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5072 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005073 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005074 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5075 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005076 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5077
5078 touch();
5079
5080 mTouchWindow->consumeAnyMotionDown();
5081}
5082
5083TEST_F(InputDispatcherUntrustedTouchesTest,
5084 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5085 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005086 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5087 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005088 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005089 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5090 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5092
5093 touch();
5094
5095 mTouchWindow->consumeAnyMotionDown();
5096}
5097
5098TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5099 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005100 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5101 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005102 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005103 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5104 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005106
5107 touch();
5108
5109 mTouchWindow->assertNoEvents();
5110}
5111
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005112TEST_F(InputDispatcherUntrustedTouchesTest,
5113 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5114 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005115 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5116 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005117 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005118 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5119 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5121
5122 touch();
5123
5124 mTouchWindow->assertNoEvents();
5125}
5126
5127TEST_F(InputDispatcherUntrustedTouchesTest,
5128 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5129 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005130 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5131 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005132 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005133 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5134 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5136
5137 touch();
5138
5139 mTouchWindow->consumeAnyMotionDown();
5140}
5141
5142TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5143 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005144 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5145 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5147
5148 touch();
5149
5150 mTouchWindow->consumeAnyMotionDown();
5151}
5152
5153TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5154 const sp<FakeWindowHandle>& w =
5155 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5157
5158 touch();
5159
5160 mTouchWindow->consumeAnyMotionDown();
5161}
5162
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005163TEST_F(InputDispatcherUntrustedTouchesTest,
5164 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5165 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5166 const sp<FakeWindowHandle>& w =
5167 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5169
5170 touch();
5171
5172 mTouchWindow->assertNoEvents();
5173}
5174
5175TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5176 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5177 const sp<FakeWindowHandle>& w =
5178 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5180
5181 touch();
5182
5183 mTouchWindow->consumeAnyMotionDown();
5184}
5185
5186TEST_F(InputDispatcherUntrustedTouchesTest,
5187 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5188 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5189 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005190 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5191 OPACITY_ABOVE_THRESHOLD);
5192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5193
5194 touch();
5195
5196 mTouchWindow->consumeAnyMotionDown();
5197}
5198
5199TEST_F(InputDispatcherUntrustedTouchesTest,
5200 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5201 const sp<FakeWindowHandle>& w1 =
5202 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5203 OPACITY_BELOW_THRESHOLD);
5204 const sp<FakeWindowHandle>& w2 =
5205 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5206 OPACITY_BELOW_THRESHOLD);
5207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5208
5209 touch();
5210
5211 mTouchWindow->assertNoEvents();
5212}
5213
5214/**
5215 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5216 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5217 * (which alone would result in allowing touches) does not affect the blocking behavior.
5218 */
5219TEST_F(InputDispatcherUntrustedTouchesTest,
5220 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5221 const sp<FakeWindowHandle>& wB =
5222 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5223 OPACITY_BELOW_THRESHOLD);
5224 const sp<FakeWindowHandle>& wC =
5225 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5226 OPACITY_BELOW_THRESHOLD);
5227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5228
5229 touch();
5230
5231 mTouchWindow->assertNoEvents();
5232}
5233
5234/**
5235 * This test is testing that a window from a different UID but with same application token doesn't
5236 * block the touch. Apps can share the application token for close UI collaboration for example.
5237 */
5238TEST_F(InputDispatcherUntrustedTouchesTest,
5239 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5240 const sp<FakeWindowHandle>& w =
5241 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5242 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5244
5245 touch();
5246
5247 mTouchWindow->consumeAnyMotionDown();
5248}
5249
arthurhungb89ccb02020-12-30 16:19:01 +08005250class InputDispatcherDragTests : public InputDispatcherTest {
5251protected:
5252 std::shared_ptr<FakeApplicationHandle> mApp;
5253 sp<FakeWindowHandle> mWindow;
5254 sp<FakeWindowHandle> mSecondWindow;
5255 sp<FakeWindowHandle> mDragWindow;
5256
5257 void SetUp() override {
5258 InputDispatcherTest::SetUp();
5259 mApp = std::make_shared<FakeApplicationHandle>();
5260 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5261 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005262 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005263
5264 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5265 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005266 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005267
5268 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5270 }
5271
5272 // Start performing drag, we will create a drag window and transfer touch to it.
5273 void performDrag() {
5274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5275 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5276 {50, 50}))
5277 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5278
5279 // Window should receive motion event.
5280 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5281
5282 // The drag window covers the entire display
5283 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5284 mDispatcher->setInputWindows(
5285 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5286
5287 // Transfer touch focus to the drag window
5288 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5289 true /* isDragDrop */);
5290 mWindow->consumeMotionCancel();
5291 mDragWindow->consumeMotionDown();
5292 }
arthurhung6d4bed92021-03-17 11:59:33 +08005293
5294 // Start performing drag, we will create a drag window and transfer touch to it.
5295 void performStylusDrag() {
5296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5297 injectMotionEvent(mDispatcher,
5298 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5299 AINPUT_SOURCE_STYLUS)
5300 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5301 .pointer(PointerBuilder(0,
5302 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5303 .x(50)
5304 .y(50))
5305 .build()));
5306 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5307
5308 // The drag window covers the entire display
5309 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5310 mDispatcher->setInputWindows(
5311 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5312
5313 // Transfer touch focus to the drag window
5314 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5315 true /* isDragDrop */);
5316 mWindow->consumeMotionCancel();
5317 mDragWindow->consumeMotionDown();
5318 }
arthurhungb89ccb02020-12-30 16:19:01 +08005319};
5320
5321TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5322 performDrag();
5323
5324 // Move on window.
5325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5326 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5327 ADISPLAY_ID_DEFAULT, {50, 50}))
5328 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5329 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5330 mWindow->consumeDragEvent(false, 50, 50);
5331 mSecondWindow->assertNoEvents();
5332
5333 // Move to another window.
5334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5335 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5336 ADISPLAY_ID_DEFAULT, {150, 50}))
5337 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5338 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5339 mWindow->consumeDragEvent(true, 150, 50);
5340 mSecondWindow->consumeDragEvent(false, 50, 50);
5341
5342 // Move back to original window.
5343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5344 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5345 ADISPLAY_ID_DEFAULT, {50, 50}))
5346 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5347 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5348 mWindow->consumeDragEvent(false, 50, 50);
5349 mSecondWindow->consumeDragEvent(true, -50, 50);
5350
5351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5352 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5353 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5354 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5355 mWindow->assertNoEvents();
5356 mSecondWindow->assertNoEvents();
5357}
5358
arthurhungf452d0b2021-01-06 00:19:52 +08005359TEST_F(InputDispatcherDragTests, DragAndDrop) {
5360 performDrag();
5361
5362 // Move on window.
5363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5364 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5365 ADISPLAY_ID_DEFAULT, {50, 50}))
5366 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5367 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5368 mWindow->consumeDragEvent(false, 50, 50);
5369 mSecondWindow->assertNoEvents();
5370
5371 // Move to another window.
5372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5373 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5374 ADISPLAY_ID_DEFAULT, {150, 50}))
5375 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5376 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5377 mWindow->consumeDragEvent(true, 150, 50);
5378 mSecondWindow->consumeDragEvent(false, 50, 50);
5379
5380 // drop to another window.
5381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5382 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5383 {150, 50}))
5384 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5385 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5386 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5387 mWindow->assertNoEvents();
5388 mSecondWindow->assertNoEvents();
5389}
5390
arthurhung6d4bed92021-03-17 11:59:33 +08005391TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5392 performStylusDrag();
5393
5394 // Move on window and keep button pressed.
5395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5396 injectMotionEvent(mDispatcher,
5397 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5398 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5399 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5400 .x(50)
5401 .y(50))
5402 .build()))
5403 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5404 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5405 mWindow->consumeDragEvent(false, 50, 50);
5406 mSecondWindow->assertNoEvents();
5407
5408 // Move to another window and release button, expect to drop item.
5409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5410 injectMotionEvent(mDispatcher,
5411 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5412 .buttonState(0)
5413 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5414 .x(150)
5415 .y(50))
5416 .build()))
5417 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5418 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5419 mWindow->assertNoEvents();
5420 mSecondWindow->assertNoEvents();
5421 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5422
5423 // nothing to the window.
5424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5425 injectMotionEvent(mDispatcher,
5426 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
5427 .buttonState(0)
5428 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5429 .x(150)
5430 .y(50))
5431 .build()))
5432 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5433 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5434 mWindow->assertNoEvents();
5435 mSecondWindow->assertNoEvents();
5436}
5437
Arthur Hung6d0571e2021-04-09 20:18:16 +08005438TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
5439 performDrag();
5440
5441 // Set second window invisible.
5442 mSecondWindow->setVisible(false);
5443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5444
5445 // Move on window.
5446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5447 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5448 ADISPLAY_ID_DEFAULT, {50, 50}))
5449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5450 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5451 mWindow->consumeDragEvent(false, 50, 50);
5452 mSecondWindow->assertNoEvents();
5453
5454 // Move to another window.
5455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5456 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5457 ADISPLAY_ID_DEFAULT, {150, 50}))
5458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5459 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5460 mWindow->consumeDragEvent(true, 150, 50);
5461 mSecondWindow->assertNoEvents();
5462
5463 // drop to another window.
5464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5465 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5466 {150, 50}))
5467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5468 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5469 mFakePolicy->assertDropTargetEquals(nullptr);
5470 mWindow->assertNoEvents();
5471 mSecondWindow->assertNoEvents();
5472}
5473
Garfield Tane84e6f92019-08-29 17:28:41 -07005474} // namespace android::inputdispatcher