blob: daa3afa7086983daf3fce7ead4e3f05ae4784698 [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>
Prabir Pradhana3ab87a2022-01-27 10:00:21 -080020#include <android-base/silent_death_test.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080021#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070022#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070023#include <binder/Binder.h>
Michael Wright8e9a8562022-02-09 13:44:29 +000024#include <fcntl.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080028#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100029
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070031#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080032#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080033#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080034
Garfield Tan1c7bc862020-01-28 13:24:04 -080035using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050036using android::gui::FocusRequest;
37using android::gui::TouchOcclusionMode;
38using android::gui::WindowInfo;
39using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080040using android::os::InputEventInjectionResult;
41using android::os::InputEventInjectionSync;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
Dominik Laskowski2f01d772022-03-23 16:01:29 -070045using namespace ftl::flag_operators;
46
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary time value.
Prabir Pradhan5735a322022-04-11 17:23:34 +000048static constexpr nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
50// An arbitrary device id.
Prabir Pradhan5735a322022-04-11 17:23:34 +000051static constexpr int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Jeff Brownf086ddb2014-02-11 14:28:48 -080053// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000054static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
55static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080056
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080057static constexpr int32_t POINTER_1_DOWN =
58 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000059static constexpr int32_t POINTER_2_DOWN =
60 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +000061static constexpr int32_t POINTER_3_DOWN =
62 AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080063static constexpr int32_t POINTER_1_UP =
64 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
65
Antonio Kantek15beb512022-06-13 22:35:41 +000066// The default pid and uid for windows created on the primary display by the test.
Prabir Pradhan5735a322022-04-11 17:23:34 +000067static constexpr int32_t WINDOW_PID = 999;
68static constexpr int32_t WINDOW_UID = 1001;
69
Antonio Kantek15beb512022-06-13 22:35:41 +000070// The default pid and uid for the windows created on the secondary display by the test.
71static constexpr int32_t SECONDARY_WINDOW_PID = 1010;
72static constexpr int32_t SECONDARY_WINDOW_UID = 1012;
73
Prabir Pradhan5735a322022-04-11 17:23:34 +000074// The default policy flags to use for event injection by tests.
75static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000077// An arbitrary pid of the gesture monitor window
78static constexpr int32_t MONITOR_PID = 2001;
79
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080080static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
81
chaviwd1c23182019-12-20 18:44:56 -080082struct PointF {
83 float x;
84 float y;
85};
Michael Wrightd02c5b62014-02-10 15:10:22 -080086
Gang Wang342c9272020-01-13 13:15:04 -050087/**
88 * Return a DOWN key event with KEYCODE_A.
89 */
90static KeyEvent getTestKeyEvent() {
91 KeyEvent event;
92
Garfield Tanfbe732e2020-01-24 11:26:14 -080093 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
94 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
95 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050096 return event;
97}
98
Siarhei Vishniakouca205502021-07-16 21:31:58 +000099static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
100 ASSERT_EQ(expectedAction, receivedAction)
101 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
102 << MotionEvent::actionToString(receivedAction);
103}
104
Michael Wrightd02c5b62014-02-10 15:10:22 -0800105// --- FakeInputDispatcherPolicy ---
106
107class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
108 InputDispatcherConfiguration mConfig;
109
Prabir Pradhanedd96402022-02-15 01:46:16 -0800110 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
111
Michael Wrightd02c5b62014-02-10 15:10:22 -0800112protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000113 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800114
115public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000116 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800117
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800118 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700119 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
120 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
121 EXPECT_EQ(event.getDisplayId(), args.displayId);
122
123 const auto& keyEvent = static_cast<const KeyEvent&>(event);
124 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
125 EXPECT_EQ(keyEvent.getAction(), args.action);
126 });
Jackal Guof9696682018-10-05 12:23:23 +0800127 }
128
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700129 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
130 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
131 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
132 EXPECT_EQ(event.getDisplayId(), args.displayId);
133
134 const auto& motionEvent = static_cast<const MotionEvent&>(event);
135 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
136 EXPECT_EQ(motionEvent.getAction(), args.action);
137 EXPECT_EQ(motionEvent.getX(0), point.x);
138 EXPECT_EQ(motionEvent.getY(0), point.y);
139 EXPECT_EQ(motionEvent.getRawX(0), point.x);
140 EXPECT_EQ(motionEvent.getRawY(0), point.y);
141 });
Jackal Guof9696682018-10-05 12:23:23 +0800142 }
143
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700144 void assertFilterInputEventWasNotCalled() {
145 std::scoped_lock lock(mLock);
146 ASSERT_EQ(nullptr, mFilteredEvent);
147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800149 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700150 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800151 ASSERT_TRUE(mConfigurationChangedTime)
152 << "Timed out waiting for configuration changed call";
153 ASSERT_EQ(*mConfigurationChangedTime, when);
154 mConfigurationChangedTime = std::nullopt;
155 }
156
157 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700158 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800159 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800160 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800161 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
162 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
163 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
164 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
165 mLastNotifySwitch = std::nullopt;
166 }
167
chaviwfd6d3512019-03-25 13:23:49 -0700168 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700169 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800170 ASSERT_EQ(touchedToken, mOnPointerDownToken);
171 mOnPointerDownToken.clear();
172 }
173
174 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700175 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800176 ASSERT_TRUE(mOnPointerDownToken == nullptr)
177 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700178 }
179
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700180 // This function must be called soon after the expected ANR timer starts,
181 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500182 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700183 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500184 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800185 std::unique_lock lock(mLock);
186 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800188 ASSERT_NO_FATAL_FAILURE(
189 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500190 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700191 }
192
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000193 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800194 const sp<WindowInfoHandle>& window) {
195 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
196 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
197 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500198 }
199
Prabir Pradhanedd96402022-02-15 01:46:16 -0800200 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
201 const sp<IBinder>& expectedToken,
202 int32_t expectedPid) {
203 std::unique_lock lock(mLock);
204 android::base::ScopedLockAssertion assumeLocked(mLock);
205 AnrResult result;
206 ASSERT_NO_FATAL_FAILURE(result =
207 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
208 const auto& [token, pid] = result;
209 ASSERT_EQ(expectedToken, token);
210 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500211 }
212
Prabir Pradhanedd96402022-02-15 01:46:16 -0800213 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000214 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500215 std::unique_lock lock(mLock);
216 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800217 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
218 const auto& [token, _] = result;
219 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000220 }
221
Prabir Pradhanedd96402022-02-15 01:46:16 -0800222 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
223 int32_t expectedPid) {
224 std::unique_lock lock(mLock);
225 android::base::ScopedLockAssertion assumeLocked(mLock);
226 AnrResult result;
227 ASSERT_NO_FATAL_FAILURE(
228 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
229 const auto& [token, pid] = result;
230 ASSERT_EQ(expectedToken, token);
231 ASSERT_EQ(expectedPid, pid);
232 }
233
234 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 sp<IBinder> getResponsiveWindowToken() {
236 std::unique_lock lock(mLock);
237 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800238 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
239 const auto& [token, _] = result;
240 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700241 }
242
243 void assertNotifyAnrWasNotCalled() {
244 std::scoped_lock lock(mLock);
245 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800246 ASSERT_TRUE(mAnrWindows.empty());
247 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500248 << "ANR was not called, but please also consume the 'connection is responsive' "
249 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700250 }
251
Garfield Tan1c7bc862020-01-28 13:24:04 -0800252 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
253 mConfig.keyRepeatTimeout = timeout;
254 mConfig.keyRepeatDelay = delay;
255 }
256
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000257 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800258 std::unique_lock lock(mLock);
259 base::ScopedLockAssertion assumeLocked(mLock);
260
261 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
262 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000263 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800264 enabled;
265 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000266 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
267 << ") to be called.";
268 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000270 auto request = *mPointerCaptureRequest;
271 mPointerCaptureRequest.reset();
272 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800273 }
274
275 void assertSetPointerCaptureNotCalled() {
276 std::unique_lock lock(mLock);
277 base::ScopedLockAssertion assumeLocked(mLock);
278
279 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000280 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000282 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800283 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000284 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800285 }
286
arthurhungf452d0b2021-01-06 00:19:52 +0800287 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
288 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800289 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800290 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800291 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800292 }
293
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800294 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
295 std::unique_lock lock(mLock);
296 base::ScopedLockAssertion assumeLocked(mLock);
297 std::optional<sp<IBinder>> receivedToken =
298 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
299 mNotifyInputChannelBroken);
300 ASSERT_TRUE(receivedToken.has_value());
301 ASSERT_EQ(token, *receivedToken);
302 }
303
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800304 /**
305 * Set policy timeout. A value of zero means next key will not be intercepted.
306 */
307 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
308 mInterceptKeyTimeout = timeout;
309 }
310
Michael Wrightd02c5b62014-02-10 15:10:22 -0800311private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700312 std::mutex mLock;
313 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
314 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
315 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
316 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800317
Prabir Pradhan99987712020-11-10 18:43:05 -0800318 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000319
320 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800321
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700322 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700323 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800324 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
325 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700326 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800327 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
328 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700329
arthurhungf452d0b2021-01-06 00:19:52 +0800330 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800331 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800332
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800333 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
334
Prabir Pradhanedd96402022-02-15 01:46:16 -0800335 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
336 // for a specific container to become non-empty. When the container is non-empty, return the
337 // first entry from the container and erase it.
338 template <class T>
339 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
340 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
341 // If there is an ANR, Dispatcher won't be idle because there are still events
342 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
343 // before checking if ANR was called.
344 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
345 // to provide it some time to act. 100ms seems reasonable.
346 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
347 const std::chrono::time_point start = std::chrono::steady_clock::now();
348 std::optional<T> token =
349 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
350 if (!token.has_value()) {
351 ADD_FAILURE() << "Did not receive the ANR callback";
352 return {};
353 }
354
355 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
356 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
357 // the dispatcher started counting before this function was called
358 if (std::chrono::abs(timeout - waited) > 100ms) {
359 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
360 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
361 << "ms, but waited "
362 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
363 << "ms instead";
364 }
365 return *token;
366 }
367
368 template <class T>
369 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
370 std::queue<T>& storage,
371 std::unique_lock<std::mutex>& lock,
372 std::condition_variable& condition)
373 REQUIRES(mLock) {
374 condition.wait_for(lock, timeout,
375 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
376 if (storage.empty()) {
377 ADD_FAILURE() << "Did not receive the expected callback";
378 return std::nullopt;
379 }
380 T item = storage.front();
381 storage.pop();
382 return std::make_optional(item);
383 }
384
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600385 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700386 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800387 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 }
389
Prabir Pradhanedd96402022-02-15 01:46:16 -0800390 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
391 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700392 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800393 ASSERT_TRUE(pid.has_value());
394 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700395 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500396 }
397
Prabir Pradhanedd96402022-02-15 01:46:16 -0800398 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
399 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500400 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800401 ASSERT_TRUE(pid.has_value());
402 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500403 mNotifyAnr.notify_all();
404 }
405
406 void notifyNoFocusedWindowAnr(
407 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
408 std::scoped_lock lock(mLock);
409 mAnrApplications.push(applicationHandle);
410 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 }
412
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800413 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
414 std::scoped_lock lock(mLock);
415 mBrokenInputChannels.push(connectionToken);
416 mNotifyInputChannelBroken.notify_all();
417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600419 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700420
Chris Yef59a2f42020-10-16 12:55:26 -0700421 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
422 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
423 const std::vector<float>& values) override {}
424
425 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
426 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000427
Chris Yefb552902021-02-03 17:18:37 -0800428 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
429
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600430 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 *outConfig = mConfig;
432 }
433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700435 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800436 switch (inputEvent->getType()) {
437 case AINPUT_EVENT_TYPE_KEY: {
438 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800439 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800440 break;
441 }
442
443 case AINPUT_EVENT_TYPE_MOTION: {
444 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800445 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800446 break;
447 }
448 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 return true;
450 }
451
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800452 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
453 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
454 // Clear intercept state when we handled the event.
455 mInterceptKeyTimeout = 0ms;
456 }
457 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600459 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600461 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800462 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
463 // Clear intercept state so we could dispatch the event in next wake.
464 mInterceptKeyTimeout = 0ms;
465 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800466 }
467
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600468 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 return false;
470 }
471
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600472 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
473 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700474 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800475 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
476 * essentially a passthrough for notifySwitch.
477 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800478 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800479 }
480
Sean Stoutb4e0a592021-02-23 07:34:53 -0800481 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800482
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600483 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700484 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700485 mOnPointerDownToken = newToken;
486 }
487
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000488 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800489 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000490 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800491 mPointerCaptureChangedCondition.notify_all();
492 }
493
arthurhungf452d0b2021-01-06 00:19:52 +0800494 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
495 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800496 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800497 mDropTargetWindowToken = token;
498 }
499
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700500 void assertFilterInputEventWasCalledInternal(
501 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700502 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800503 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700504 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800505 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800506 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507};
508
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509// --- InputDispatcherTest ---
510
511class InputDispatcherTest : public testing::Test {
512protected:
513 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700514 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000516 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700517 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800518 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800519 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000520 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700521 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
523
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000524 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700525 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800526 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700527 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800528 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700529
530 /**
531 * Used for debugging when writing the test
532 */
533 void dumpDispatcherState() {
534 std::string dump;
535 mDispatcher->dump(dump);
536 std::stringstream ss(dump);
537 std::string to;
538
539 while (std::getline(ss, to, '\n')) {
540 ALOGE("%s", to.c_str());
541 }
542 }
Vishnu Nair958da932020-08-21 17:12:37 -0700543
chaviw3277faf2021-05-19 16:45:23 -0500544 void setFocusedWindow(const sp<WindowInfoHandle>& window,
545 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700546 FocusRequest request;
547 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000548 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700549 if (focusedWindow) {
550 request.focusedToken = focusedWindow->getToken();
551 }
552 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
553 request.displayId = window->getInfo()->displayId;
554 mDispatcher->setFocusedWindow(request);
555 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556};
557
Michael Wrightd02c5b62014-02-10 15:10:22 -0800558TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
559 KeyEvent event;
560
561 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800562 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
563 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600564 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
565 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800566 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000567 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
568 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569 << "Should reject key events with undefined action.";
570
571 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800572 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
573 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600574 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800575 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000576 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
577 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578 << "Should reject key events with ACTION_MULTIPLE.";
579}
580
581TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
582 MotionEvent event;
583 PointerProperties pointerProperties[MAX_POINTERS + 1];
584 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800585 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 pointerProperties[i].clear();
587 pointerProperties[i].id = i;
588 pointerCoords[i].clear();
589 }
590
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800591 // Some constants commonly used below
592 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
593 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
594 constexpr int32_t metaState = AMETA_NONE;
595 constexpr MotionClassification classification = MotionClassification::NONE;
596
chaviw9eaa22c2020-07-01 16:21:27 -0700597 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800599 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700600 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
601 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700602 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
603 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000606 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
607 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with undefined action.";
609
610 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800612 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
613 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
614 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
615 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500616 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800617 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000618 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
619 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 << "Should reject motion events with pointer down index too large.";
621
Garfield Tanfbe732e2020-01-24 11:26:14 -0800622 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700623 AMOTION_EVENT_ACTION_POINTER_DOWN |
624 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700625 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
626 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700627 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500628 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000630 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
631 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 << "Should reject motion events with pointer down index too small.";
633
634 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800635 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800636 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
637 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
638 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
639 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500640 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800641 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000642 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
643 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 << "Should reject motion events with pointer up index too large.";
645
Garfield Tanfbe732e2020-01-24 11:26:14 -0800646 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700647 AMOTION_EVENT_ACTION_POINTER_UP |
648 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700649 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
650 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700651 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500652 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800653 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000654 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
655 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800656 << "Should reject motion events with pointer up index too small.";
657
658 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800659 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
660 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700661 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
663 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000666 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
667 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 << "Should reject motion events with 0 pointers.";
669
Garfield Tanfbe732e2020-01-24 11:26:14 -0800670 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
671 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700672 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700673 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
674 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700675 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800676 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000677 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
678 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800679 << "Should reject motion events with more than MAX_POINTERS pointers.";
680
681 // Rejects motion events with invalid pointer ids.
682 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800683 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
684 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700685 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700686 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
687 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700688 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800689 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000690 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
691 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 << "Should reject motion events with pointer ids less than 0.";
693
694 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800695 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
696 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700697 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700698 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
699 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700700 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800701 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000702 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
703 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800704 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
705
706 // Rejects motion events with duplicate pointer ids.
707 pointerProperties[0].id = 1;
708 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800709 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
710 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700711 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700712 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
713 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700714 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800715 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000716 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
717 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718 << "Should reject motion events with duplicate pointer ids.";
719}
720
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800721/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
722
723TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
724 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800725 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800726 mDispatcher->notifyConfigurationChanged(&args);
727 ASSERT_TRUE(mDispatcher->waitForIdle());
728
729 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
730}
731
732TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800733 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
734 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800735 mDispatcher->notifySwitch(&args);
736
737 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
738 args.policyFlags |= POLICY_FLAG_TRUSTED;
739 mFakePolicy->assertNotifySwitchWasCalled(args);
740}
741
Arthur Hungb92218b2018-08-14 12:00:21 +0800742// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700743static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700744// Default input dispatching timeout if there is no focused application or paused window
745// from which to determine an appropriate dispatching timeout.
746static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
747 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
748 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800749
750class FakeApplicationHandle : public InputApplicationHandle {
751public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700752 FakeApplicationHandle() {
753 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700754 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500755 mInfo.dispatchingTimeoutMillis =
756 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700757 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800758 virtual ~FakeApplicationHandle() {}
759
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000760 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700761
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500762 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
763 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700764 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800765};
766
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800767class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800768public:
Garfield Tan15601662020-09-22 15:32:38 -0700769 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800770 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700771 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800772 }
773
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800774 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700775 InputEvent* event;
776 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
777 if (!consumeSeq) {
778 return nullptr;
779 }
780 finishEvent(*consumeSeq);
781 return event;
782 }
783
784 /**
785 * Receive an event without acknowledging it.
786 * Return the sequence number that could later be used to send finished signal.
787 */
788 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800789 uint32_t consumeSeq;
790 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800791
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800792 std::chrono::time_point start = std::chrono::steady_clock::now();
793 status_t status = WOULD_BLOCK;
794 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800795 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800796 &event);
797 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
798 if (elapsed > 100ms) {
799 break;
800 }
801 }
802
803 if (status == WOULD_BLOCK) {
804 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700805 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800806 }
807
808 if (status != OK) {
809 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700810 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800811 }
812 if (event == nullptr) {
813 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700814 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700816 if (outEvent != nullptr) {
817 *outEvent = event;
818 }
819 return consumeSeq;
820 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800821
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700822 /**
823 * To be used together with "receiveEvent" to complete the consumption of an event.
824 */
825 void finishEvent(uint32_t consumeSeq) {
826 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
827 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800828 }
829
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000830 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
831 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
832 ASSERT_EQ(OK, status);
833 }
834
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000835 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
836 std::optional<int32_t> expectedDisplayId,
837 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800838 InputEvent* event = consume();
839
840 ASSERT_NE(nullptr, event) << mName.c_str()
841 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800842 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700843 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800844 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800845
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000846 if (expectedDisplayId.has_value()) {
847 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
848 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800849
Tiger Huang8664f8c2018-10-11 19:14:35 +0800850 switch (expectedEventType) {
851 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800852 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
853 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000854 if (expectedFlags.has_value()) {
855 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
856 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800857 break;
858 }
859 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800860 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000861 assertMotionAction(expectedAction, motionEvent.getAction());
862
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000863 if (expectedFlags.has_value()) {
864 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
865 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800866 break;
867 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100868 case AINPUT_EVENT_TYPE_FOCUS: {
869 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
870 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800871 case AINPUT_EVENT_TYPE_CAPTURE: {
872 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
873 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000874 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
875 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
876 }
arthurhungb89ccb02020-12-30 16:19:01 +0800877 case AINPUT_EVENT_TYPE_DRAG: {
878 FAIL() << "Use 'consumeDragEvent' for DRAG events";
879 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800880 default: {
881 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
882 }
883 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800884 }
885
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100886 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
887 InputEvent* event = consume();
888 ASSERT_NE(nullptr, event) << mName.c_str()
889 << ": consumer should have returned non-NULL event.";
890 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
891 << "Got " << inputEventTypeToString(event->getType())
892 << " event instead of FOCUS event";
893
894 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
895 << mName.c_str() << ": event displayId should always be NONE.";
896
897 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
898 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100899 }
900
Prabir Pradhan99987712020-11-10 18:43:05 -0800901 void consumeCaptureEvent(bool hasCapture) {
902 const InputEvent* event = consume();
903 ASSERT_NE(nullptr, event) << mName.c_str()
904 << ": consumer should have returned non-NULL event.";
905 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
906 << "Got " << inputEventTypeToString(event->getType())
907 << " event instead of CAPTURE event";
908
909 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
910 << mName.c_str() << ": event displayId should always be NONE.";
911
912 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
913 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
914 }
915
arthurhungb89ccb02020-12-30 16:19:01 +0800916 void consumeDragEvent(bool isExiting, float x, float y) {
917 const InputEvent* event = consume();
918 ASSERT_NE(nullptr, event) << mName.c_str()
919 << ": consumer should have returned non-NULL event.";
920 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
921 << "Got " << inputEventTypeToString(event->getType())
922 << " event instead of DRAG event";
923
924 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
925 << mName.c_str() << ": event displayId should always be NONE.";
926
927 const auto& dragEvent = static_cast<const DragEvent&>(*event);
928 EXPECT_EQ(isExiting, dragEvent.isExiting());
929 EXPECT_EQ(x, dragEvent.getX());
930 EXPECT_EQ(y, dragEvent.getY());
931 }
932
Antonio Kantekf16f2832021-09-28 04:39:20 +0000933 void consumeTouchModeEvent(bool inTouchMode) {
934 const InputEvent* event = consume();
935 ASSERT_NE(nullptr, event) << mName.c_str()
936 << ": consumer should have returned non-NULL event.";
937 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
938 << "Got " << inputEventTypeToString(event->getType())
939 << " event instead of TOUCH_MODE event";
940
941 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
942 << mName.c_str() << ": event displayId should always be NONE.";
943 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
944 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
945 }
946
chaviwd1c23182019-12-20 18:44:56 -0800947 void assertNoEvents() {
948 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700949 if (event == nullptr) {
950 return;
951 }
952 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
953 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
954 ADD_FAILURE() << "Received key event "
955 << KeyEvent::actionToString(keyEvent.getAction());
956 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
957 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
958 ADD_FAILURE() << "Received motion event "
959 << MotionEvent::actionToString(motionEvent.getAction());
960 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
961 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
962 ADD_FAILURE() << "Received focus event, hasFocus = "
963 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800964 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
965 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
966 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
967 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000968 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
969 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
970 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
971 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700972 }
973 FAIL() << mName.c_str()
974 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800975 }
976
977 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
978
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800979 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
980
chaviwd1c23182019-12-20 18:44:56 -0800981protected:
982 std::unique_ptr<InputConsumer> mConsumer;
983 PreallocatedInputEventFactory mEventFactory;
984
985 std::string mName;
986};
987
chaviw3277faf2021-05-19 16:45:23 -0500988class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800989public:
990 static const int32_t WIDTH = 600;
991 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800992
Chris Yea209fde2020-07-22 13:54:51 -0700993 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700994 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500995 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800996 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500997 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700998 base::Result<std::unique_ptr<InputChannel>> channel =
999 dispatcher->createInputChannel(name);
1000 token = (*channel)->getConnectionToken();
1001 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001002 }
1003
1004 inputApplicationHandle->updateInfo();
1005 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1006
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001007 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001008 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001009 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001010 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001011 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001012 mInfo.frameLeft = 0;
1013 mInfo.frameTop = 0;
1014 mInfo.frameRight = WIDTH;
1015 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001016 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001017 mInfo.globalScaleFactor = 1.0;
1018 mInfo.touchableRegion.clear();
1019 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001020 mInfo.ownerPid = WINDOW_PID;
1021 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001022 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001023 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001024 }
1025
Arthur Hungabbb9d82021-09-01 14:52:30 +00001026 sp<FakeWindowHandle> clone(
1027 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001028 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001029 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001030 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1031 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001032 return handle;
1033 }
1034
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001035 void setTouchable(bool touchable) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1037 }
chaviwd1c23182019-12-20 18:44:56 -08001038
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001039 void setFocusable(bool focusable) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1041 }
1042
1043 void setVisible(bool visible) {
1044 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1045 }
Vishnu Nair958da932020-08-21 17:12:37 -07001046
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001047 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001048 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001049 }
1050
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001051 void setPaused(bool paused) {
1052 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1053 }
1054
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001055 void setPreventSplitting(bool preventSplitting) {
1056 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001057 }
1058
1059 void setSlippery(bool slippery) {
1060 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1061 }
1062
1063 void setWatchOutsideTouch(bool watchOutside) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1065 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001066
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001067 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1068
1069 void setInterceptsStylus(bool interceptsStylus) {
1070 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1071 }
1072
1073 void setDropInput(bool dropInput) {
1074 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1075 }
1076
1077 void setDropInputIfObscured(bool dropInputIfObscured) {
1078 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1079 }
1080
1081 void setNoInputChannel(bool noInputChannel) {
1082 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1083 }
1084
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001085 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1086
chaviw3277faf2021-05-19 16:45:23 -05001087 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001088
Bernardo Rufino7393d172021-02-26 13:56:11 +00001089 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1090
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001091 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001092 mInfo.frameLeft = frame.left;
1093 mInfo.frameTop = frame.top;
1094 mInfo.frameRight = frame.right;
1095 mInfo.frameBottom = frame.bottom;
1096 mInfo.touchableRegion.clear();
1097 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001098
1099 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1100 ui::Transform translate;
1101 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1102 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001103 }
1104
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001105 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1106
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001107 void setIsWallpaper(bool isWallpaper) {
1108 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1109 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001110
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001111 void setDupTouchToWallpaper(bool hasWallpaper) {
1112 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1113 }
chaviwd1c23182019-12-20 18:44:56 -08001114
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001115 void setTrustedOverlay(bool trustedOverlay) {
1116 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1117 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001118
chaviw9eaa22c2020-07-01 16:21:27 -07001119 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1120 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1121 }
1122
1123 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001124
yunho.shinf4a80b82020-11-16 21:13:57 +09001125 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1126
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001127 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1128 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1129 expectedFlags);
1130 }
1131
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001132 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1133 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1134 }
1135
Svet Ganov5d3bc372020-01-26 23:11:07 -08001136 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001137 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001138 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1139 expectedFlags);
1140 }
1141
1142 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001143 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001144 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1145 expectedFlags);
1146 }
1147
1148 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001149 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001150 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1151 }
1152
1153 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1154 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001155 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1156 expectedFlags);
1157 }
1158
Svet Ganov5d3bc372020-01-26 23:11:07 -08001159 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001160 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1161 int32_t expectedFlags = 0) {
1162 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1163 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001164 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1165 }
1166
1167 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001168 int32_t expectedFlags = 0) {
1169 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1170 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001171 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1172 }
1173
1174 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001175 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001176 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1177 expectedFlags);
1178 }
1179
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001180 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1181 int32_t expectedFlags = 0) {
1182 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1183 expectedFlags);
1184 }
1185
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001186 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1187 int32_t expectedFlags = 0) {
1188 InputEvent* event = consume();
1189 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1190 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1191 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1192 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1193 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1194 }
1195
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001196 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1200 }
1201
Prabir Pradhan99987712020-11-10 18:43:05 -08001202 void consumeCaptureEvent(bool hasCapture) {
1203 ASSERT_NE(mInputReceiver, nullptr)
1204 << "Cannot consume events from a window with no receiver";
1205 mInputReceiver->consumeCaptureEvent(hasCapture);
1206 }
1207
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001208 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1209 std::optional<int32_t> expectedDisplayId,
1210 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001211 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1212 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1213 expectedFlags);
1214 }
1215
arthurhungb89ccb02020-12-30 16:19:01 +08001216 void consumeDragEvent(bool isExiting, float x, float y) {
1217 mInputReceiver->consumeDragEvent(isExiting, x, y);
1218 }
1219
Antonio Kantekf16f2832021-09-28 04:39:20 +00001220 void consumeTouchModeEvent(bool inTouchMode) {
1221 ASSERT_NE(mInputReceiver, nullptr)
1222 << "Cannot consume events from a window with no receiver";
1223 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1224 }
1225
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001226 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001227 if (mInputReceiver == nullptr) {
1228 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1229 return std::nullopt;
1230 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001231 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001232 }
1233
1234 void finishEvent(uint32_t sequenceNum) {
1235 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1236 mInputReceiver->finishEvent(sequenceNum);
1237 }
1238
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001239 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1240 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1241 mInputReceiver->sendTimeline(inputEventId, timeline);
1242 }
1243
chaviwaf87b3e2019-10-01 16:59:28 -07001244 InputEvent* consume() {
1245 if (mInputReceiver == nullptr) {
1246 return nullptr;
1247 }
1248 return mInputReceiver->consume();
1249 }
1250
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001251 MotionEvent* consumeMotion() {
1252 InputEvent* event = consume();
1253 if (event == nullptr) {
1254 ADD_FAILURE() << "Consume failed : no event";
1255 return nullptr;
1256 }
1257 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1258 ADD_FAILURE() << "Instead of motion event, got "
1259 << inputEventTypeToString(event->getType());
1260 return nullptr;
1261 }
1262 return static_cast<MotionEvent*>(event);
1263 }
1264
Arthur Hungb92218b2018-08-14 12:00:21 +08001265 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001266 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001267 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001268 return; // Can't receive events if the window does not have input channel
1269 }
1270 ASSERT_NE(nullptr, mInputReceiver)
1271 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001272 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001273 }
1274
chaviwaf87b3e2019-10-01 16:59:28 -07001275 sp<IBinder> getToken() { return mInfo.token; }
1276
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001277 const std::string& getName() { return mName; }
1278
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001279 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1280 mInfo.ownerPid = ownerPid;
1281 mInfo.ownerUid = ownerUid;
1282 }
1283
Prabir Pradhanedd96402022-02-15 01:46:16 -08001284 int32_t getPid() const { return mInfo.ownerPid; }
1285
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001286 void destroyReceiver() { mInputReceiver = nullptr; }
1287
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001288 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1289
chaviwd1c23182019-12-20 18:44:56 -08001290private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001291 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001292 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001293 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001294};
1295
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001296std::atomic<int32_t> FakeWindowHandle::sId{1};
1297
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001298static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001299 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001300 int32_t displayId = ADISPLAY_ID_NONE,
1301 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001302 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001303 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1304 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001305 KeyEvent event;
1306 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1307
1308 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001309 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001310 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1311 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001312
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001313 if (!allowKeyRepeat) {
1314 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1315 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001316 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001317 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001318}
1319
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001320static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001321 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001322 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1323}
1324
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001325// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1326// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1327// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001328static InputEventInjectionResult injectKeyDownNoRepeat(
1329 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001330 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1331 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1332 /* allowKeyRepeat */ false);
1333}
1334
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001335static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001336 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001337 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1338}
1339
Garfield Tandf26e862020-07-01 20:18:19 -07001340class PointerBuilder {
1341public:
1342 PointerBuilder(int32_t id, int32_t toolType) {
1343 mProperties.clear();
1344 mProperties.id = id;
1345 mProperties.toolType = toolType;
1346 mCoords.clear();
1347 }
1348
1349 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1350
1351 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1352
1353 PointerBuilder& axis(int32_t axis, float value) {
1354 mCoords.setAxisValue(axis, value);
1355 return *this;
1356 }
1357
1358 PointerProperties buildProperties() const { return mProperties; }
1359
1360 PointerCoords buildCoords() const { return mCoords; }
1361
1362private:
1363 PointerProperties mProperties;
1364 PointerCoords mCoords;
1365};
1366
1367class MotionEventBuilder {
1368public:
1369 MotionEventBuilder(int32_t action, int32_t source) {
1370 mAction = action;
1371 mSource = source;
1372 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1373 }
1374
1375 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1376 mEventTime = eventTime;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& displayId(int32_t displayId) {
1381 mDisplayId = displayId;
1382 return *this;
1383 }
1384
1385 MotionEventBuilder& actionButton(int32_t actionButton) {
1386 mActionButton = actionButton;
1387 return *this;
1388 }
1389
arthurhung6d4bed92021-03-17 11:59:33 +08001390 MotionEventBuilder& buttonState(int32_t buttonState) {
1391 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001392 return *this;
1393 }
1394
1395 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1396 mRawXCursorPosition = rawXCursorPosition;
1397 return *this;
1398 }
1399
1400 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1401 mRawYCursorPosition = rawYCursorPosition;
1402 return *this;
1403 }
1404
1405 MotionEventBuilder& pointer(PointerBuilder pointer) {
1406 mPointers.push_back(pointer);
1407 return *this;
1408 }
1409
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001410 MotionEventBuilder& addFlag(uint32_t flags) {
1411 mFlags |= flags;
1412 return *this;
1413 }
1414
Garfield Tandf26e862020-07-01 20:18:19 -07001415 MotionEvent build() {
1416 std::vector<PointerProperties> pointerProperties;
1417 std::vector<PointerCoords> pointerCoords;
1418 for (const PointerBuilder& pointer : mPointers) {
1419 pointerProperties.push_back(pointer.buildProperties());
1420 pointerCoords.push_back(pointer.buildCoords());
1421 }
1422
1423 // Set mouse cursor position for the most common cases to avoid boilerplate.
1424 if (mSource == AINPUT_SOURCE_MOUSE &&
1425 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1426 mPointers.size() == 1) {
1427 mRawXCursorPosition = pointerCoords[0].getX();
1428 mRawYCursorPosition = pointerCoords[0].getY();
1429 }
1430
1431 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001432 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001433 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001434 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001435 mButtonState, MotionClassification::NONE, identityTransform,
1436 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001437 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1438 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001439
1440 return event;
1441 }
1442
1443private:
1444 int32_t mAction;
1445 int32_t mSource;
1446 nsecs_t mEventTime;
1447 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1448 int32_t mActionButton{0};
1449 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001450 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001451 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1452 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1453
1454 std::vector<PointerBuilder> mPointers;
1455};
1456
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001457static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001458 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001459 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001460 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1461 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1462 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1463 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001464}
1465
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001467 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001468 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001469 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001470 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1471 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001473 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1474 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001475 MotionEvent event = MotionEventBuilder(action, source)
1476 .displayId(displayId)
1477 .eventTime(eventTime)
1478 .rawXCursorPosition(cursorPosition.x)
1479 .rawYCursorPosition(cursorPosition.y)
1480 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1481 .x(position.x)
1482 .y(position.y))
1483 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001484
1485 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001486 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1487 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001488}
1489
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001490static InputEventInjectionResult injectMotionDown(
1491 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1492 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001493 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001494}
1495
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001496static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001497 int32_t source, int32_t displayId,
1498 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001499 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001500}
1501
Jackal Guof9696682018-10-05 12:23:23 +08001502static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1503 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1504 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001505 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1506 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1507 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001508
1509 return args;
1510}
1511
chaviwd1c23182019-12-20 18:44:56 -08001512static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1513 const std::vector<PointF>& points) {
1514 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001515 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1516 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1517 }
1518
chaviwd1c23182019-12-20 18:44:56 -08001519 PointerProperties pointerProperties[pointerCount];
1520 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001521
chaviwd1c23182019-12-20 18:44:56 -08001522 for (size_t i = 0; i < pointerCount; i++) {
1523 pointerProperties[i].clear();
1524 pointerProperties[i].id = i;
1525 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001526
chaviwd1c23182019-12-20 18:44:56 -08001527 pointerCoords[i].clear();
1528 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1529 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1530 }
Jackal Guof9696682018-10-05 12:23:23 +08001531
1532 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1533 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001534 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001535 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1536 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001537 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1538 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001539 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1540 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001541
1542 return args;
1543}
1544
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001545static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1546 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1547}
1548
chaviwd1c23182019-12-20 18:44:56 -08001549static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1550 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1551}
1552
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001553static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1554 const PointerCaptureRequest& request) {
1555 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001556}
1557
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001558/**
1559 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1560 * broken channel.
1561 */
1562TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1563 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1564 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001565 sp<FakeWindowHandle>::make(application, mDispatcher,
1566 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001567
1568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1569
1570 // Window closes its channel, but the window remains.
1571 window->destroyReceiver();
1572 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1573}
1574
Arthur Hungb92218b2018-08-14 12:00:21 +08001575TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001576 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001577 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1578 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001579
Arthur Hung72d8dc32020-03-28 00:48:39 +00001580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1582 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001584
1585 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001586 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001587}
1588
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001589TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1590 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001591 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1592 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001593
1594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1595 // Inject a MotionEvent to an unknown display.
1596 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1597 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1598 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1599
1600 // Window should receive motion event.
1601 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1602}
1603
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001604/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001605 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606 * This test serves as a sanity check for the next test, where setInputWindows is
1607 * called twice.
1608 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001609TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001610 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001611 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1612 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001613 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001614
1615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1618 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001620
1621 // Window should receive motion event.
1622 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1623}
1624
1625/**
1626 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001627 */
1628TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001630 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1631 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001632 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001633
1634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001637 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1638 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001640
1641 // Window should receive motion event.
1642 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1643}
1644
Arthur Hungb92218b2018-08-14 12:00:21 +08001645// The foreground window should receive the first touch down event.
1646TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001647 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001648 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001649 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001650 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001651 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001652
Arthur Hung72d8dc32020-03-28 00:48:39 +00001653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1655 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001657
1658 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001659 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001660 windowSecond->assertNoEvents();
1661}
1662
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001663/**
1664 * Two windows: A top window, and a wallpaper behind the window.
1665 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1666 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001667 * 1. foregroundWindow <-- dup touch to wallpaper
1668 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001669 */
1670TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1671 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1672 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001673 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001674 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001675 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001676 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001677 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001678 constexpr int expectedWallpaperFlags =
1679 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1680
1681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1683 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1684 {100, 200}))
1685 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1686
1687 // Both foreground window and its wallpaper should receive the touch down
1688 foregroundWindow->consumeMotionDown();
1689 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1690
1691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1692 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1693 ADISPLAY_ID_DEFAULT, {110, 200}))
1694 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1695
1696 foregroundWindow->consumeMotionMove();
1697 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1698
1699 // Now the foreground window goes away, but the wallpaper stays
1700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1701 foregroundWindow->consumeMotionCancel();
1702 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1703 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1704}
1705
1706/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001707 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1708 * with the following differences:
1709 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1710 * clean up the connection.
1711 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1712 * Ensure that there's no crash in the dispatcher.
1713 */
1714TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1715 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1716 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001717 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001718 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001719 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001720 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001721 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001722 constexpr int expectedWallpaperFlags =
1723 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1724
1725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1727 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1728 {100, 200}))
1729 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1730
1731 // Both foreground window and its wallpaper should receive the touch down
1732 foregroundWindow->consumeMotionDown();
1733 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1734
1735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1736 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1737 ADISPLAY_ID_DEFAULT, {110, 200}))
1738 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1739
1740 foregroundWindow->consumeMotionMove();
1741 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1742
1743 // Wallpaper closes its channel, but the window remains.
1744 wallpaperWindow->destroyReceiver();
1745 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1746
1747 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1748 // is no longer valid.
1749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1750 foregroundWindow->consumeMotionCancel();
1751}
1752
1753/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001754 * A single window that receives touch (on top), and a wallpaper window underneath it.
1755 * The top window gets a multitouch gesture.
1756 * Ensure that wallpaper gets the same gesture.
1757 */
1758TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1759 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1760 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001761 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001762 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001763
1764 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001765 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001766 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001767 constexpr int expectedWallpaperFlags =
1768 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1769
1770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1771
1772 // Touch down on top window
1773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1774 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1775 {100, 100}))
1776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1777
1778 // Both top window and its wallpaper should receive the touch down
1779 window->consumeMotionDown();
1780 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1781
1782 // Second finger down on the top window
1783 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001784 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001785 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1786 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1787 .x(100)
1788 .y(100))
1789 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1790 .x(150)
1791 .y(150))
1792 .build();
1793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1794 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1795 InputEventInjectionSync::WAIT_FOR_RESULT))
1796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1797
1798 window->consumeMotionPointerDown(1 /* pointerIndex */);
1799 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1800 expectedWallpaperFlags);
1801 window->assertNoEvents();
1802 wallpaperWindow->assertNoEvents();
1803}
1804
1805/**
1806 * Two windows: a window on the left and window on the right.
1807 * A third window, wallpaper, is behind both windows, and spans both top windows.
1808 * The first touch down goes to the left window. A second pointer touches down on the right window.
1809 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1810 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1811 * ACTION_POINTER_DOWN(1).
1812 */
1813TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1815 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001816 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001817 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001818 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001819
1820 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001821 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001822 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001823 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001824
1825 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001826 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001827 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001828 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001829 constexpr int expectedWallpaperFlags =
1830 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1831
1832 mDispatcher->setInputWindows(
1833 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1834
1835 // Touch down on left window
1836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1838 {100, 100}))
1839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1840
1841 // Both foreground window and its wallpaper should receive the touch down
1842 leftWindow->consumeMotionDown();
1843 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1844
1845 // Second finger down on the right window
1846 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001847 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001848 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1849 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1850 .x(100)
1851 .y(100))
1852 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1853 .x(300)
1854 .y(100))
1855 .build();
1856 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1857 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1858 InputEventInjectionSync::WAIT_FOR_RESULT))
1859 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1860
1861 leftWindow->consumeMotionMove();
1862 // Since the touch is split, right window gets ACTION_DOWN
1863 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1864 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1865 expectedWallpaperFlags);
1866
1867 // Now, leftWindow, which received the first finger, disappears.
1868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1869 leftWindow->consumeMotionCancel();
1870 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1871 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1872
1873 // The pointer that's still down on the right window moves, and goes to the right window only.
1874 // As far as the dispatcher's concerned though, both pointers are still present.
1875 const MotionEvent secondFingerMoveEvent =
1876 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1877 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1878 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1879 .x(100)
1880 .y(100))
1881 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1882 .x(310)
1883 .y(110))
1884 .build();
1885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1886 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1887 InputEventInjectionSync::WAIT_FOR_RESULT));
1888 rightWindow->consumeMotionMove();
1889
1890 leftWindow->assertNoEvents();
1891 rightWindow->assertNoEvents();
1892 wallpaperWindow->assertNoEvents();
1893}
1894
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001895/**
1896 * On the display, have a single window, and also an area where there's no window.
1897 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1898 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1899 */
1900TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1901 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1902 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001903 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001904
1905 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1906 NotifyMotionArgs args;
1907
1908 // Touch down on the empty space
1909 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1910
1911 mDispatcher->waitForIdle();
1912 window->assertNoEvents();
1913
1914 // Now touch down on the window with another pointer
1915 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1916 mDispatcher->waitForIdle();
1917 window->consumeMotionDown();
1918}
1919
1920/**
1921 * Same test as above, but instead of touching the empty space, the first touch goes to
1922 * non-touchable window.
1923 */
1924TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1925 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1926 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001927 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001928 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1929 window1->setTouchable(false);
1930 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001931 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001932 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1933
1934 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1935
1936 NotifyMotionArgs args;
1937 // Touch down on the non-touchable window
1938 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1939
1940 mDispatcher->waitForIdle();
1941 window1->assertNoEvents();
1942 window2->assertNoEvents();
1943
1944 // Now touch down on the window with another pointer
1945 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1946 mDispatcher->waitForIdle();
1947 window2->consumeMotionDown();
1948}
1949
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001950/**
1951 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
1952 * to the event time of the first ACTION_DOWN sent to the particular window.
1953 */
1954TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
1955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1956 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001957 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001958 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1959 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001960 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001961 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1962
1963 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1964
1965 NotifyMotionArgs args;
1966 // Touch down on the first window
1967 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1968
1969 mDispatcher->waitForIdle();
1970 InputEvent* inputEvent1 = window1->consume();
1971 window2->assertNoEvents();
1972 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
1973 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
1974 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
1975
1976 // Now touch down on the window with another pointer
1977 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1978 mDispatcher->waitForIdle();
1979 InputEvent* inputEvent2 = window2->consume();
1980 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
1981 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
1982 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
1983 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
1984
1985 // Now move the pointer on the second window
1986 mDispatcher->notifyMotion(
1987 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
1988 mDispatcher->waitForIdle();
1989 InputEvent* inputEvent3 = window2->consume();
1990 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
1991 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
1992
1993 // Now add new touch down on the second window
1994 mDispatcher->notifyMotion(
1995 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
1996 mDispatcher->waitForIdle();
1997 InputEvent* inputEvent4 = window2->consume();
1998 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
1999 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
2000
2001 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2002 window1->consumeMotionMove();
2003 window1->assertNoEvents();
2004
2005 // Now move the pointer on the first window
2006 mDispatcher->notifyMotion(
2007 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2008 mDispatcher->waitForIdle();
2009 InputEvent* inputEvent5 = window1->consume();
2010 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2011 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2012
2013 mDispatcher->notifyMotion(&(
2014 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2015 mDispatcher->waitForIdle();
2016 InputEvent* inputEvent6 = window1->consume();
2017 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2018 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2019}
2020
Garfield Tandf26e862020-07-01 20:18:19 -07002021TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002022 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002023 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002024 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002025 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002026 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002027 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002028 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002029
2030 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2031
2032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2033
2034 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002036 injectMotionEvent(mDispatcher,
2037 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2038 AINPUT_SOURCE_MOUSE)
2039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2040 .x(900)
2041 .y(400))
2042 .build()));
2043 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2044 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2045 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2046 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2047
2048 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002050 injectMotionEvent(mDispatcher,
2051 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2052 AINPUT_SOURCE_MOUSE)
2053 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2054 .x(300)
2055 .y(400))
2056 .build()));
2057 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2058 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2059 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2060 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2061 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2062 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2063
2064 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002066 injectMotionEvent(mDispatcher,
2067 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2068 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2069 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2070 .x(300)
2071 .y(400))
2072 .build()));
2073 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2074
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002076 injectMotionEvent(mDispatcher,
2077 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2078 AINPUT_SOURCE_MOUSE)
2079 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2080 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2081 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2082 .x(300)
2083 .y(400))
2084 .build()));
2085 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2086 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2087
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002088 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002089 injectMotionEvent(mDispatcher,
2090 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2091 AINPUT_SOURCE_MOUSE)
2092 .buttonState(0)
2093 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2094 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2095 .x(300)
2096 .y(400))
2097 .build()));
2098 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2099 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2100
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002102 injectMotionEvent(mDispatcher,
2103 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2104 .buttonState(0)
2105 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2106 .x(300)
2107 .y(400))
2108 .build()));
2109 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2110
2111 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002113 injectMotionEvent(mDispatcher,
2114 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2115 AINPUT_SOURCE_MOUSE)
2116 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2117 .x(900)
2118 .y(400))
2119 .build()));
2120 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2121 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2122 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2123 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2124 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2125 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2126}
2127
2128// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2129// directly in this test.
2130TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002131 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002132 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002133 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002134 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002135
2136 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2137
2138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2139
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002141 injectMotionEvent(mDispatcher,
2142 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2143 AINPUT_SOURCE_MOUSE)
2144 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2145 .x(300)
2146 .y(400))
2147 .build()));
2148 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2149 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2150
2151 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002152 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002153 injectMotionEvent(mDispatcher,
2154 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2155 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2156 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2157 .x(300)
2158 .y(400))
2159 .build()));
2160 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2161
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002163 injectMotionEvent(mDispatcher,
2164 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2165 AINPUT_SOURCE_MOUSE)
2166 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2167 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2168 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2169 .x(300)
2170 .y(400))
2171 .build()));
2172 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2173 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2174
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002175 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002176 injectMotionEvent(mDispatcher,
2177 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2178 AINPUT_SOURCE_MOUSE)
2179 .buttonState(0)
2180 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2181 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2182 .x(300)
2183 .y(400))
2184 .build()));
2185 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2186 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2187
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002188 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002189 injectMotionEvent(mDispatcher,
2190 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2191 .buttonState(0)
2192 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2193 .x(300)
2194 .y(400))
2195 .build()));
2196 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2197
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002198 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002199 injectMotionEvent(mDispatcher,
2200 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2201 AINPUT_SOURCE_MOUSE)
2202 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2203 .x(300)
2204 .y(400))
2205 .build()));
2206 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2207 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2208}
2209
Garfield Tan00f511d2019-06-12 16:55:40 -07002210TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002211 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002212
2213 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002214 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002215 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002216 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002217 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002218 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002219
2220 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2221
Arthur Hung72d8dc32020-03-28 00:48:39 +00002222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002223
2224 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2225 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002227 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002228 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002229 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002230 windowRight->assertNoEvents();
2231}
2232
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002233TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002234 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002235 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2236 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002237 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002238
Arthur Hung72d8dc32020-03-28 00:48:39 +00002239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002240 setFocusedWindow(window);
2241
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002242 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002243
2244 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2245 mDispatcher->notifyKey(&keyArgs);
2246
2247 // Window should receive key down event.
2248 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2249
2250 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2251 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002252 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002253 mDispatcher->notifyDeviceReset(&args);
2254 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2255 AKEY_EVENT_FLAG_CANCELED);
2256}
2257
2258TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002260 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2261 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002262
Arthur Hung72d8dc32020-03-28 00:48:39 +00002263 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002264
2265 NotifyMotionArgs motionArgs =
2266 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2267 ADISPLAY_ID_DEFAULT);
2268 mDispatcher->notifyMotion(&motionArgs);
2269
2270 // Window should receive motion down event.
2271 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2272
2273 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2274 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002275 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002276 mDispatcher->notifyDeviceReset(&args);
2277 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2278 0 /*expectedFlags*/);
2279}
2280
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002281TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2282 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002283 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2284 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002285 window->setFocusable(true);
2286
2287 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2288 setFocusedWindow(window);
2289
2290 window->consumeFocusEvent(true);
2291
2292 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2293 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2294 const nsecs_t injectTime = keyArgs.eventTime;
2295 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2296 mDispatcher->notifyKey(&keyArgs);
2297 // The dispatching time should be always greater than or equal to intercept key timeout.
2298 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2299 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2300 std::chrono::nanoseconds(interceptKeyTimeout).count());
2301}
2302
2303TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002305 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2306 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002307 window->setFocusable(true);
2308
2309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2310 setFocusedWindow(window);
2311
2312 window->consumeFocusEvent(true);
2313
2314 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2315 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2316 mFakePolicy->setInterceptKeyTimeout(150ms);
2317 mDispatcher->notifyKey(&keyDown);
2318 mDispatcher->notifyKey(&keyUp);
2319
2320 // Window should receive key event immediately when same key up.
2321 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2322 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2323}
2324
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002325/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002326 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2327 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2328 * ACTION_OUTSIDE event is sent per gesture.
2329 */
2330TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2331 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2332 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002333 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2334 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002335 window->setWatchOutsideTouch(true);
2336 window->setFrame(Rect{0, 0, 100, 100});
2337 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002338 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2339 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002340 secondWindow->setFrame(Rect{100, 100, 200, 200});
2341 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002342 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2343 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002344 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2346
2347 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2348 NotifyMotionArgs motionArgs =
2349 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2350 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2351 mDispatcher->notifyMotion(&motionArgs);
2352 window->assertNoEvents();
2353 secondWindow->assertNoEvents();
2354
2355 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2356 // Now, `window` should get ACTION_OUTSIDE.
2357 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2358 {PointF{-10, -10}, PointF{105, 105}});
2359 mDispatcher->notifyMotion(&motionArgs);
2360 window->consumeMotionOutside();
2361 secondWindow->consumeMotionDown();
2362 thirdWindow->assertNoEvents();
2363
2364 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2365 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2366 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2367 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2368 mDispatcher->notifyMotion(&motionArgs);
2369 window->assertNoEvents();
2370 secondWindow->consumeMotionMove();
2371 thirdWindow->consumeMotionDown();
2372}
2373
Prabir Pradhan814fe082022-07-22 20:22:18 +00002374TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2375 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002376 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2377 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002378 window->setFocusable(true);
2379
2380 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2381 setFocusedWindow(window);
2382
2383 window->consumeFocusEvent(true);
2384
2385 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2386 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2387 mDispatcher->notifyKey(&keyDown);
2388 mDispatcher->notifyKey(&keyUp);
2389
2390 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2391 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2392
2393 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2394 mDispatcher->onWindowInfosChanged({}, {});
2395
2396 window->consumeFocusEvent(false);
2397
2398 mDispatcher->notifyKey(&keyDown);
2399 mDispatcher->notifyKey(&keyUp);
2400 window->assertNoEvents();
2401}
2402
Arthur Hung96483742022-11-15 03:30:48 +00002403TEST_F(InputDispatcherTest, NonSplitTouchableWindowReceivesMultiTouch) {
2404 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2405 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2406 "Fake Window", ADISPLAY_ID_DEFAULT);
2407 // Ensure window is non-split and have some transform.
2408 window->setPreventSplitting(true);
2409 window->setWindowOffset(20, 40);
2410 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2411
2412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2413 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2414 {50, 50}))
2415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2416 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2417
2418 const MotionEvent secondFingerDownEvent =
2419 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2420 .displayId(ADISPLAY_ID_DEFAULT)
2421 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2422 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
2423 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
2424 .x(-30)
2425 .y(-50))
2426 .build();
2427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2428 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
2429 InputEventInjectionSync::WAIT_FOR_RESULT))
2430 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2431
2432 const MotionEvent* event = window->consumeMotion();
2433 EXPECT_EQ(POINTER_1_DOWN, event->getAction());
2434 EXPECT_EQ(70, event->getX(0)); // 50 + 20
2435 EXPECT_EQ(90, event->getY(0)); // 50 + 40
2436 EXPECT_EQ(-10, event->getX(1)); // -30 + 20
2437 EXPECT_EQ(-10, event->getY(1)); // -50 + 40
2438}
2439
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002440/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002441 * Ensure the correct coordinate spaces are used by InputDispatcher.
2442 *
2443 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2444 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2445 * space.
2446 */
2447class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2448public:
2449 void SetUp() override {
2450 InputDispatcherTest::SetUp();
2451 mDisplayInfos.clear();
2452 mWindowInfos.clear();
2453 }
2454
2455 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2456 gui::DisplayInfo info;
2457 info.displayId = displayId;
2458 info.transform = transform;
2459 mDisplayInfos.push_back(std::move(info));
2460 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2461 }
2462
2463 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2464 mWindowInfos.push_back(*windowHandle->getInfo());
2465 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2466 }
2467
2468 // Set up a test scenario where the display has a scaled projection and there are two windows
2469 // on the display.
2470 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2471 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2472 // respectively.
2473 ui::Transform displayTransform;
2474 displayTransform.set(2, 0, 0, 4);
2475 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2476
2477 std::shared_ptr<FakeApplicationHandle> application =
2478 std::make_shared<FakeApplicationHandle>();
2479
2480 // Add two windows to the display. Their frames are represented in the display space.
2481 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002482 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2483 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002484 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2485 addWindow(firstWindow);
2486
2487 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002488 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2489 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002490 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2491 addWindow(secondWindow);
2492 return {std::move(firstWindow), std::move(secondWindow)};
2493 }
2494
2495private:
2496 std::vector<gui::DisplayInfo> mDisplayInfos;
2497 std::vector<gui::WindowInfo> mWindowInfos;
2498};
2499
2500TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2501 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2502 // Send down to the first window. The point is represented in the display space. The point is
2503 // selected so that if the hit test was done with the transform applied to it, then it would
2504 // end up in the incorrect window.
2505 NotifyMotionArgs downMotionArgs =
2506 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2507 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2508 mDispatcher->notifyMotion(&downMotionArgs);
2509
2510 firstWindow->consumeMotionDown();
2511 secondWindow->assertNoEvents();
2512}
2513
2514// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2515// the event should be treated as being in the logical display space.
2516TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2517 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2518 // Send down to the first window. The point is represented in the logical display space. The
2519 // point is selected so that if the hit test was done in logical display space, then it would
2520 // end up in the incorrect window.
2521 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2522 PointF{75 * 2, 55 * 4});
2523
2524 firstWindow->consumeMotionDown();
2525 secondWindow->assertNoEvents();
2526}
2527
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002528// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2529// event should be treated as being in the logical display space.
2530TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2531 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2532
2533 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2534 ui::Transform injectedEventTransform;
2535 injectedEventTransform.set(matrix);
2536 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2537 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2538
2539 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2540 .displayId(ADISPLAY_ID_DEFAULT)
2541 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2542 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2543 .x(untransformedPoint.x)
2544 .y(untransformedPoint.y))
2545 .build();
2546 event.transform(matrix);
2547
2548 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2549 InputEventInjectionSync::WAIT_FOR_RESULT);
2550
2551 firstWindow->consumeMotionDown();
2552 secondWindow->assertNoEvents();
2553}
2554
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002555TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2556 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2557
2558 // Send down to the second window.
2559 NotifyMotionArgs downMotionArgs =
2560 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2561 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2562 mDispatcher->notifyMotion(&downMotionArgs);
2563
2564 firstWindow->assertNoEvents();
2565 const MotionEvent* event = secondWindow->consumeMotion();
2566 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2567
2568 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2569 EXPECT_EQ(300, event->getRawX(0));
2570 EXPECT_EQ(880, event->getRawY(0));
2571
2572 // Ensure that the x and y values are in the window's coordinate space.
2573 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2574 // the logical display space. This will be the origin of the window space.
2575 EXPECT_EQ(100, event->getX(0));
2576 EXPECT_EQ(80, event->getY(0));
2577}
2578
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002579using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2580 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002581
2582class TransferTouchFixture : public InputDispatcherTest,
2583 public ::testing::WithParamInterface<TransferFunction> {};
2584
2585TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002587
2588 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002589 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002590 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2591 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002592 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002593 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2594 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002595
2596 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002598
2599 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002600 NotifyMotionArgs downMotionArgs =
2601 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2602 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002603 mDispatcher->notifyMotion(&downMotionArgs);
2604 // Only the first window should get the down event
2605 firstWindow->consumeMotionDown();
2606 secondWindow->assertNoEvents();
2607
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002608 // Transfer touch to the second window
2609 TransferFunction f = GetParam();
2610 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2611 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002612 // The first window gets cancel and the second gets down
2613 firstWindow->consumeMotionCancel();
2614 secondWindow->consumeMotionDown();
2615
2616 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002617 NotifyMotionArgs upMotionArgs =
2618 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2619 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002620 mDispatcher->notifyMotion(&upMotionArgs);
2621 // The first window gets no events and the second gets up
2622 firstWindow->assertNoEvents();
2623 secondWindow->consumeMotionUp();
2624}
2625
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002626/**
2627 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2628 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2629 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2630 * natural to the user.
2631 * In this test, we are sending a pointer to both spy window and first window. We then try to
2632 * transfer touch to the second window. The dispatcher should identify the first window as the
2633 * one that should lose the gesture, and therefore the action should be to move the gesture from
2634 * the first window to the second.
2635 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2636 * the other API, as well.
2637 */
2638TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2640
2641 // Create a couple of windows + a spy window
2642 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002643 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002644 spyWindow->setTrustedOverlay(true);
2645 spyWindow->setSpy(true);
2646 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002647 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002648 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002649 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002650
2651 // Add the windows to the dispatcher
2652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2653
2654 // Send down to the first window
2655 NotifyMotionArgs downMotionArgs =
2656 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2657 ADISPLAY_ID_DEFAULT);
2658 mDispatcher->notifyMotion(&downMotionArgs);
2659 // Only the first window and spy should get the down event
2660 spyWindow->consumeMotionDown();
2661 firstWindow->consumeMotionDown();
2662
2663 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2664 // if f === 'transferTouch'.
2665 TransferFunction f = GetParam();
2666 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2667 ASSERT_TRUE(success);
2668 // The first window gets cancel and the second gets down
2669 firstWindow->consumeMotionCancel();
2670 secondWindow->consumeMotionDown();
2671
2672 // Send up event to the second window
2673 NotifyMotionArgs upMotionArgs =
2674 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2675 ADISPLAY_ID_DEFAULT);
2676 mDispatcher->notifyMotion(&upMotionArgs);
2677 // The first window gets no events and the second+spy get up
2678 firstWindow->assertNoEvents();
2679 spyWindow->consumeMotionUp();
2680 secondWindow->consumeMotionUp();
2681}
2682
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002683TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002684 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002685
2686 PointF touchPoint = {10, 10};
2687
2688 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002689 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002690 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2691 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002692 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002693 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002694 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2695 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002696 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002697
2698 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002700
2701 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002702 NotifyMotionArgs downMotionArgs =
2703 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2704 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002705 mDispatcher->notifyMotion(&downMotionArgs);
2706 // Only the first window should get the down event
2707 firstWindow->consumeMotionDown();
2708 secondWindow->assertNoEvents();
2709
2710 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002711 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002712 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002713 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002714 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2715 // Only the first window should get the pointer down event
2716 firstWindow->consumeMotionPointerDown(1);
2717 secondWindow->assertNoEvents();
2718
2719 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002720 TransferFunction f = GetParam();
2721 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2722 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002723 // The first window gets cancel and the second gets down and pointer down
2724 firstWindow->consumeMotionCancel();
2725 secondWindow->consumeMotionDown();
2726 secondWindow->consumeMotionPointerDown(1);
2727
2728 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002729 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002730 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002731 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002732 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2733 // The first window gets nothing and the second gets pointer up
2734 firstWindow->assertNoEvents();
2735 secondWindow->consumeMotionPointerUp(1);
2736
2737 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002738 NotifyMotionArgs upMotionArgs =
2739 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2740 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002741 mDispatcher->notifyMotion(&upMotionArgs);
2742 // The first window gets nothing and the second gets up
2743 firstWindow->assertNoEvents();
2744 secondWindow->consumeMotionUp();
2745}
2746
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002747// For the cases of single pointer touch and two pointers non-split touch, the api's
2748// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2749// for the case where there are multiple pointers split across several windows.
2750INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2751 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002752 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2753 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002754 return dispatcher->transferTouch(destChannelToken,
2755 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002756 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002757 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2758 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002759 return dispatcher->transferTouchFocus(from, to,
2760 false /*isDragAndDrop*/);
2761 }));
2762
Svet Ganov5d3bc372020-01-26 23:11:07 -08002763TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002764 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002765
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002766 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002767 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2768 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002769 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002770
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002771 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002772 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2773 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002774 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002775
2776 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002778
2779 PointF pointInFirst = {300, 200};
2780 PointF pointInSecond = {300, 600};
2781
2782 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002783 NotifyMotionArgs firstDownMotionArgs =
2784 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2785 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002786 mDispatcher->notifyMotion(&firstDownMotionArgs);
2787 // Only the first window should get the down event
2788 firstWindow->consumeMotionDown();
2789 secondWindow->assertNoEvents();
2790
2791 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002792 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002793 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002794 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002795 mDispatcher->notifyMotion(&secondDownMotionArgs);
2796 // The first window gets a move and the second a down
2797 firstWindow->consumeMotionMove();
2798 secondWindow->consumeMotionDown();
2799
2800 // Transfer touch focus to the second window
2801 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2802 // The first window gets cancel and the new gets pointer down (it already saw down)
2803 firstWindow->consumeMotionCancel();
2804 secondWindow->consumeMotionPointerDown(1);
2805
2806 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002807 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002808 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002809 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002810 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2811 // The first window gets nothing and the second gets pointer up
2812 firstWindow->assertNoEvents();
2813 secondWindow->consumeMotionPointerUp(1);
2814
2815 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002816 NotifyMotionArgs upMotionArgs =
2817 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2818 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002819 mDispatcher->notifyMotion(&upMotionArgs);
2820 // The first window gets nothing and the second gets up
2821 firstWindow->assertNoEvents();
2822 secondWindow->consumeMotionUp();
2823}
2824
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002825// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2826// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2827// touch is not supported, so the touch should continue on those windows and the transferred-to
2828// window should get nothing.
2829TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2830 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2831
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002832 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002833 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2834 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002835 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002836
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002837 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002838 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2839 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002840 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002841
2842 // Add the windows to the dispatcher
2843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2844
2845 PointF pointInFirst = {300, 200};
2846 PointF pointInSecond = {300, 600};
2847
2848 // Send down to the first window
2849 NotifyMotionArgs firstDownMotionArgs =
2850 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2851 ADISPLAY_ID_DEFAULT, {pointInFirst});
2852 mDispatcher->notifyMotion(&firstDownMotionArgs);
2853 // Only the first window should get the down event
2854 firstWindow->consumeMotionDown();
2855 secondWindow->assertNoEvents();
2856
2857 // Send down to the second window
2858 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002859 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002860 {pointInFirst, pointInSecond});
2861 mDispatcher->notifyMotion(&secondDownMotionArgs);
2862 // The first window gets a move and the second a down
2863 firstWindow->consumeMotionMove();
2864 secondWindow->consumeMotionDown();
2865
2866 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002867 const bool transferred =
2868 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002869 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2870 ASSERT_FALSE(transferred);
2871 firstWindow->assertNoEvents();
2872 secondWindow->assertNoEvents();
2873
2874 // The rest of the dispatch should proceed as normal
2875 // Send pointer up to the second window
2876 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002877 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002878 {pointInFirst, pointInSecond});
2879 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2880 // The first window gets MOVE and the second gets pointer up
2881 firstWindow->consumeMotionMove();
2882 secondWindow->consumeMotionUp();
2883
2884 // Send up event to the first window
2885 NotifyMotionArgs upMotionArgs =
2886 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2887 ADISPLAY_ID_DEFAULT);
2888 mDispatcher->notifyMotion(&upMotionArgs);
2889 // The first window gets nothing and the second gets up
2890 firstWindow->consumeMotionUp();
2891 secondWindow->assertNoEvents();
2892}
2893
Arthur Hungabbb9d82021-09-01 14:52:30 +00002894// This case will create two windows and one mirrored window on the default display and mirror
2895// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2896// the windows info of second display before default display.
2897TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2898 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2899 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002900 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002901 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002902 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002903 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002904 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002905
2906 sp<FakeWindowHandle> mirrorWindowInPrimary =
2907 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2908 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002909
2910 sp<FakeWindowHandle> firstWindowInSecondary =
2911 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2912 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002913
2914 sp<FakeWindowHandle> secondWindowInSecondary =
2915 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2916 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002917
2918 // Update window info, let it find window handle of second display first.
2919 mDispatcher->setInputWindows(
2920 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2921 {ADISPLAY_ID_DEFAULT,
2922 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2923
2924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2926 {50, 50}))
2927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2928
2929 // Window should receive motion event.
2930 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2931
2932 // Transfer touch focus
2933 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2934 secondWindowInPrimary->getToken()));
2935 // The first window gets cancel.
2936 firstWindowInPrimary->consumeMotionCancel();
2937 secondWindowInPrimary->consumeMotionDown();
2938
2939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2940 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2941 ADISPLAY_ID_DEFAULT, {150, 50}))
2942 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2943 firstWindowInPrimary->assertNoEvents();
2944 secondWindowInPrimary->consumeMotionMove();
2945
2946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2947 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2948 {150, 50}))
2949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2950 firstWindowInPrimary->assertNoEvents();
2951 secondWindowInPrimary->consumeMotionUp();
2952}
2953
2954// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2955// 'transferTouch' api.
2956TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2957 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2958 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002959 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002960 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002961 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002962 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002963 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002964
2965 sp<FakeWindowHandle> mirrorWindowInPrimary =
2966 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2967 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002968
2969 sp<FakeWindowHandle> firstWindowInSecondary =
2970 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2971 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002972
2973 sp<FakeWindowHandle> secondWindowInSecondary =
2974 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2975 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002976
2977 // Update window info, let it find window handle of second display first.
2978 mDispatcher->setInputWindows(
2979 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2980 {ADISPLAY_ID_DEFAULT,
2981 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2982
2983 // Touch on second display.
2984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2985 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2987
2988 // Window should receive motion event.
2989 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2990
2991 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002992 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002993
2994 // The first window gets cancel.
2995 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2996 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2997
2998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2999 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3000 SECOND_DISPLAY_ID, {150, 50}))
3001 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3002 firstWindowInPrimary->assertNoEvents();
3003 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
3004
3005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3006 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
3007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3008 firstWindowInPrimary->assertNoEvents();
3009 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
3010}
3011
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003013 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003014 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3015 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003016
Vishnu Nair47074b82020-08-14 11:54:47 -07003017 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003019 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020
3021 window->consumeFocusEvent(true);
3022
3023 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3024 mDispatcher->notifyKey(&keyArgs);
3025
3026 // Window should receive key down event.
3027 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3028}
3029
3030TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003031 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003032 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3033 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003034
Arthur Hung72d8dc32020-03-28 00:48:39 +00003035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003036
3037 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3038 mDispatcher->notifyKey(&keyArgs);
3039 mDispatcher->waitForIdle();
3040
3041 window->assertNoEvents();
3042}
3043
3044// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3045TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003046 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003047 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3048 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003049
Arthur Hung72d8dc32020-03-28 00:48:39 +00003050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003051
3052 // Send key
3053 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3054 mDispatcher->notifyKey(&keyArgs);
3055 // Send motion
3056 NotifyMotionArgs motionArgs =
3057 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3058 ADISPLAY_ID_DEFAULT);
3059 mDispatcher->notifyMotion(&motionArgs);
3060
3061 // Window should receive only the motion event
3062 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3063 window->assertNoEvents(); // Key event or focus event will not be received
3064}
3065
arthurhungea3f4fc2020-12-21 23:18:53 +08003066TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3067 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3068
arthurhungea3f4fc2020-12-21 23:18:53 +08003069 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003070 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3071 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003072 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003073
arthurhungea3f4fc2020-12-21 23:18:53 +08003074 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003075 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3076 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003077 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003078
3079 // Add the windows to the dispatcher
3080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3081
3082 PointF pointInFirst = {300, 200};
3083 PointF pointInSecond = {300, 600};
3084
3085 // Send down to the first window
3086 NotifyMotionArgs firstDownMotionArgs =
3087 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3088 ADISPLAY_ID_DEFAULT, {pointInFirst});
3089 mDispatcher->notifyMotion(&firstDownMotionArgs);
3090 // Only the first window should get the down event
3091 firstWindow->consumeMotionDown();
3092 secondWindow->assertNoEvents();
3093
3094 // Send down to the second window
3095 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003096 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003097 {pointInFirst, pointInSecond});
3098 mDispatcher->notifyMotion(&secondDownMotionArgs);
3099 // The first window gets a move and the second a down
3100 firstWindow->consumeMotionMove();
3101 secondWindow->consumeMotionDown();
3102
3103 // Send pointer cancel to the second window
3104 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003105 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003106 {pointInFirst, pointInSecond});
3107 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3108 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3109 // The first window gets move and the second gets cancel.
3110 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3111 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3112
3113 // Send up event.
3114 NotifyMotionArgs upMotionArgs =
3115 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3116 ADISPLAY_ID_DEFAULT);
3117 mDispatcher->notifyMotion(&upMotionArgs);
3118 // The first window gets up and the second gets nothing.
3119 firstWindow->consumeMotionUp();
3120 secondWindow->assertNoEvents();
3121}
3122
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003123TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3124 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3125
3126 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003127 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3129 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3130 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3131 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3132
3133 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3134 window->assertNoEvents();
3135 mDispatcher->waitForIdle();
3136}
3137
chaviwd1c23182019-12-20 18:44:56 -08003138class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003139public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003140 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003141 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003142 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003143 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003144 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003145 }
3146
chaviwd1c23182019-12-20 18:44:56 -08003147 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3148
3149 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3150 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3151 expectedDisplayId, expectedFlags);
3152 }
3153
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003154 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3155
3156 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3157
chaviwd1c23182019-12-20 18:44:56 -08003158 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3159 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3160 expectedDisplayId, expectedFlags);
3161 }
3162
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003163 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3164 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3165 expectedDisplayId, expectedFlags);
3166 }
3167
chaviwd1c23182019-12-20 18:44:56 -08003168 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3169 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3170 expectedDisplayId, expectedFlags);
3171 }
3172
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003173 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3174 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3175 expectedDisplayId, expectedFlags);
3176 }
3177
Arthur Hungfbfa5722021-11-16 02:45:54 +00003178 void consumeMotionPointerDown(int32_t pointerIdx) {
3179 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3180 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3181 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3182 0 /*expectedFlags*/);
3183 }
3184
Evan Rosky84f07f02021-04-16 10:42:42 -07003185 MotionEvent* consumeMotion() {
3186 InputEvent* event = mInputReceiver->consume();
3187 if (!event) {
3188 ADD_FAILURE() << "No event was produced";
3189 return nullptr;
3190 }
3191 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3192 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3193 return nullptr;
3194 }
3195 return static_cast<MotionEvent*>(event);
3196 }
3197
chaviwd1c23182019-12-20 18:44:56 -08003198 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3199
3200private:
3201 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003202};
3203
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003204using InputDispatcherMonitorTest = InputDispatcherTest;
3205
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003206/**
3207 * Two entities that receive touch: A window, and a global monitor.
3208 * The touch goes to the window, and then the window disappears.
3209 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3210 * for the monitor, as well.
3211 * 1. foregroundWindow
3212 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3213 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003214TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003215 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3216 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003217 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003218
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003219 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003220
3221 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3223 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3224 {100, 200}))
3225 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3226
3227 // Both the foreground window and the global monitor should receive the touch down
3228 window->consumeMotionDown();
3229 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3230
3231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3232 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3233 ADISPLAY_ID_DEFAULT, {110, 200}))
3234 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3235
3236 window->consumeMotionMove();
3237 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3238
3239 // Now the foreground window goes away
3240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3241 window->consumeMotionCancel();
3242 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3243
3244 // If more events come in, there will be no more foreground window to send them to. This will
3245 // cause a cancel for the monitor, as well.
3246 ASSERT_EQ(InputEventInjectionResult::FAILED,
3247 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3248 ADISPLAY_ID_DEFAULT, {120, 200}))
3249 << "Injection should fail because the window was removed";
3250 window->assertNoEvents();
3251 // Global monitor now gets the cancel
3252 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3253}
3254
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003255TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003256 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003257 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3258 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003260
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003261 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003262
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003263 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003264 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003265 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003266 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003267 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003268}
3269
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003270TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3271 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003272
Chris Yea209fde2020-07-22 13:54:51 -07003273 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003274 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3275 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003276 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003277
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003279 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003280 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003281 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003282 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003283
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003284 // Pilfer pointers from the monitor.
3285 // This should not do anything and the window should continue to receive events.
3286 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003287
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003289 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3290 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003291 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003292
3293 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3294 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003295}
3296
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003297TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003298 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003299 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3300 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3302 window->setWindowOffset(20, 40);
3303 window->setWindowTransform(0, 1, -1, 0);
3304
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003305 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003306
3307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3308 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3309 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3310 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3311 MotionEvent* event = monitor.consumeMotion();
3312 // Even though window has transform, gesture monitor must not.
3313 ASSERT_EQ(ui::Transform(), event->getTransform());
3314}
3315
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003316TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003317 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003318 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003319
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003320 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003321 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003322 << "Injection should fail if there is a monitor, but no touchable window";
3323 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003324}
3325
chaviw81e2bb92019-12-18 15:03:51 -08003326TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003328 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3329 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003330
Arthur Hung72d8dc32020-03-28 00:48:39 +00003331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003332
3333 NotifyMotionArgs motionArgs =
3334 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3335 ADISPLAY_ID_DEFAULT);
3336
3337 mDispatcher->notifyMotion(&motionArgs);
3338 // Window should receive motion down event.
3339 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3340
3341 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003342 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003343 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3344 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3345 motionArgs.pointerCoords[0].getX() - 10);
3346
3347 mDispatcher->notifyMotion(&motionArgs);
3348 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3349 0 /*expectedFlags*/);
3350}
3351
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003352/**
3353 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3354 * the device default right away. In the test scenario, we check both the default value,
3355 * and the action of enabling / disabling.
3356 */
3357TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003358 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003359 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3360 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003361 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003362
3363 // Set focused application.
3364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003365 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003366
3367 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003369 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003370 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3371
3372 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003373 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003375 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3376
3377 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003378 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003379 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003380 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003381 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003383 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003384 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3385
3386 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003387 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003389 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3390
3391 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003392 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003393 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003394 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003395 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003397 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003398 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3399
3400 window->assertNoEvents();
3401}
3402
Gang Wange9087892020-01-07 12:17:14 -05003403TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003404 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003405 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3406 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003407
3408 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003409 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003410
Arthur Hung72d8dc32020-03-28 00:48:39 +00003411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003412 setFocusedWindow(window);
3413
Gang Wange9087892020-01-07 12:17:14 -05003414 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3415
3416 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3417 mDispatcher->notifyKey(&keyArgs);
3418
3419 InputEvent* event = window->consume();
3420 ASSERT_NE(event, nullptr);
3421
3422 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3423 ASSERT_NE(verified, nullptr);
3424 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3425
3426 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3427 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3428 ASSERT_EQ(keyArgs.source, verified->source);
3429 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3430
3431 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3432
3433 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003434 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003435 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003436 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3437 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3438 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3439 ASSERT_EQ(0, verifiedKey.repeatCount);
3440}
3441
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003442TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003443 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003444 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3445 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003446
3447 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3448
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003449 ui::Transform transform;
3450 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3451
3452 gui::DisplayInfo displayInfo;
3453 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3454 displayInfo.transform = transform;
3455
3456 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003457
3458 NotifyMotionArgs motionArgs =
3459 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3460 ADISPLAY_ID_DEFAULT);
3461 mDispatcher->notifyMotion(&motionArgs);
3462
3463 InputEvent* event = window->consume();
3464 ASSERT_NE(event, nullptr);
3465
3466 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3467 ASSERT_NE(verified, nullptr);
3468 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3469
3470 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3471 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3472 EXPECT_EQ(motionArgs.source, verified->source);
3473 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3474
3475 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3476
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003477 const vec2 rawXY =
3478 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3479 motionArgs.pointerCoords[0].getXYValue());
3480 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3481 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003482 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003483 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003484 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003485 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3486 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3487}
3488
chaviw09c8d2d2020-08-24 15:48:26 -07003489/**
3490 * Ensure that separate calls to sign the same data are generating the same key.
3491 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3492 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3493 * tests.
3494 */
3495TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3496 KeyEvent event = getTestKeyEvent();
3497 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3498
3499 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3500 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3501 ASSERT_EQ(hmac1, hmac2);
3502}
3503
3504/**
3505 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3506 */
3507TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3508 KeyEvent event = getTestKeyEvent();
3509 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3510 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3511
3512 verifiedEvent.deviceId += 1;
3513 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3514
3515 verifiedEvent.source += 1;
3516 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3517
3518 verifiedEvent.eventTimeNanos += 1;
3519 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3520
3521 verifiedEvent.displayId += 1;
3522 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3523
3524 verifiedEvent.action += 1;
3525 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3526
3527 verifiedEvent.downTimeNanos += 1;
3528 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3529
3530 verifiedEvent.flags += 1;
3531 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3532
3533 verifiedEvent.keyCode += 1;
3534 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3535
3536 verifiedEvent.scanCode += 1;
3537 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3538
3539 verifiedEvent.metaState += 1;
3540 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3541
3542 verifiedEvent.repeatCount += 1;
3543 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3544}
3545
Vishnu Nair958da932020-08-21 17:12:37 -07003546TEST_F(InputDispatcherTest, SetFocusedWindow) {
3547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3548 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003549 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003550 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003551 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003552 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3553
3554 // Top window is also focusable but is not granted focus.
3555 windowTop->setFocusable(true);
3556 windowSecond->setFocusable(true);
3557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3558 setFocusedWindow(windowSecond);
3559
3560 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3562 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003563
3564 // Focused window should receive event.
3565 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3566 windowTop->assertNoEvents();
3567}
3568
3569TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3570 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3571 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003572 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003573 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3574
3575 window->setFocusable(true);
3576 // Release channel for window is no longer valid.
3577 window->releaseChannel();
3578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3579 setFocusedWindow(window);
3580
3581 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003582 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3583 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003584
3585 // window channel is invalid, so it should not receive any input event.
3586 window->assertNoEvents();
3587}
3588
3589TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3590 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3591 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003592 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003593 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003594 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3595
Vishnu Nair958da932020-08-21 17:12:37 -07003596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3597 setFocusedWindow(window);
3598
3599 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003600 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3601 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003602
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003603 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003604 window->assertNoEvents();
3605}
3606
3607TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3608 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3609 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003610 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003611 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003612 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003613 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3614
3615 windowTop->setFocusable(true);
3616 windowSecond->setFocusable(true);
3617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3618 setFocusedWindow(windowTop);
3619 windowTop->consumeFocusEvent(true);
3620
3621 setFocusedWindow(windowSecond, windowTop);
3622 windowSecond->consumeFocusEvent(true);
3623 windowTop->consumeFocusEvent(false);
3624
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3626 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003627
3628 // Focused window should receive event.
3629 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3630}
3631
3632TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3633 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3634 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003635 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003636 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003637 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003638 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3639
3640 windowTop->setFocusable(true);
3641 windowSecond->setFocusable(true);
3642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3643 setFocusedWindow(windowSecond, windowTop);
3644
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003645 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3646 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003647
3648 // Event should be dropped.
3649 windowTop->assertNoEvents();
3650 windowSecond->assertNoEvents();
3651}
3652
3653TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3654 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3655 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003656 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003657 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003658 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3659 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003660 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3661
3662 window->setFocusable(true);
3663 previousFocusedWindow->setFocusable(true);
3664 window->setVisible(false);
3665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3666 setFocusedWindow(previousFocusedWindow);
3667 previousFocusedWindow->consumeFocusEvent(true);
3668
3669 // Requesting focus on invisible window takes focus from currently focused window.
3670 setFocusedWindow(window);
3671 previousFocusedWindow->consumeFocusEvent(false);
3672
3673 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003675 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003676 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003677
3678 // Window does not get focus event or key down.
3679 window->assertNoEvents();
3680
3681 // Window becomes visible.
3682 window->setVisible(true);
3683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3684
3685 // Window receives focus event.
3686 window->consumeFocusEvent(true);
3687 // Focused window receives key down.
3688 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3689}
3690
Vishnu Nair599f1412021-06-21 10:39:58 -07003691TEST_F(InputDispatcherTest, DisplayRemoved) {
3692 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3693 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003694 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003695 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3696
3697 // window is granted focus.
3698 window->setFocusable(true);
3699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3700 setFocusedWindow(window);
3701 window->consumeFocusEvent(true);
3702
3703 // When a display is removed window loses focus.
3704 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3705 window->consumeFocusEvent(false);
3706}
3707
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003708/**
3709 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3710 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3711 * of the 'slipperyEnterWindow'.
3712 *
3713 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3714 * a way so that the touched location is no longer covered by the top window.
3715 *
3716 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3717 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3718 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3719 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3720 * with ACTION_DOWN).
3721 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3722 * window moved itself away from the touched location and had Flag::SLIPPERY.
3723 *
3724 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3725 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3726 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3727 *
3728 * In this test, we ensure that the event received by the bottom window has
3729 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3730 */
3731TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003732 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3733 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003734
3735 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3736 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3737
3738 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003739 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003740 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003741 // Make sure this one overlaps the bottom window
3742 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3743 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3744 // one. Windows with the same owner are not considered to be occluding each other.
3745 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3746
3747 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003748 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003749 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3750
3751 mDispatcher->setInputWindows(
3752 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3753
3754 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3755 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3756 ADISPLAY_ID_DEFAULT, {{50, 50}});
3757 mDispatcher->notifyMotion(&args);
3758 slipperyExitWindow->consumeMotionDown();
3759 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3760 mDispatcher->setInputWindows(
3761 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3762
3763 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3764 ADISPLAY_ID_DEFAULT, {{51, 51}});
3765 mDispatcher->notifyMotion(&args);
3766
3767 slipperyExitWindow->consumeMotionCancel();
3768
3769 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3770 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3771}
3772
Garfield Tan1c7bc862020-01-28 13:24:04 -08003773class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3774protected:
3775 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3776 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3777
Chris Yea209fde2020-07-22 13:54:51 -07003778 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003779 sp<FakeWindowHandle> mWindow;
3780
3781 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003782 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003783 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003784 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003785 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3786 ASSERT_EQ(OK, mDispatcher->start());
3787
3788 setUpWindow();
3789 }
3790
3791 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003792 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003793 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003794
Vishnu Nair47074b82020-08-14 11:54:47 -07003795 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003797 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003798 mWindow->consumeFocusEvent(true);
3799 }
3800
Chris Ye2ad95392020-09-01 13:44:44 -07003801 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003802 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003803 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003804 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3805 mDispatcher->notifyKey(&keyArgs);
3806
3807 // Window should receive key down event.
3808 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3809 }
3810
3811 void expectKeyRepeatOnce(int32_t repeatCount) {
3812 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3813 InputEvent* repeatEvent = mWindow->consume();
3814 ASSERT_NE(nullptr, repeatEvent);
3815
3816 uint32_t eventType = repeatEvent->getType();
3817 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3818
3819 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3820 uint32_t eventAction = repeatKeyEvent->getAction();
3821 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3822 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3823 }
3824
Chris Ye2ad95392020-09-01 13:44:44 -07003825 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003826 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003827 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003828 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3829 mDispatcher->notifyKey(&keyArgs);
3830
3831 // Window should receive key down event.
3832 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3833 0 /*expectedFlags*/);
3834 }
3835};
3836
3837TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003838 sendAndConsumeKeyDown(1 /* deviceId */);
3839 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3840 expectKeyRepeatOnce(repeatCount);
3841 }
3842}
3843
3844TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3845 sendAndConsumeKeyDown(1 /* deviceId */);
3846 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3847 expectKeyRepeatOnce(repeatCount);
3848 }
3849 sendAndConsumeKeyDown(2 /* deviceId */);
3850 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003851 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3852 expectKeyRepeatOnce(repeatCount);
3853 }
3854}
3855
3856TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003857 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003858 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003859 sendAndConsumeKeyUp(1 /* deviceId */);
3860 mWindow->assertNoEvents();
3861}
3862
3863TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3864 sendAndConsumeKeyDown(1 /* deviceId */);
3865 expectKeyRepeatOnce(1 /*repeatCount*/);
3866 sendAndConsumeKeyDown(2 /* deviceId */);
3867 expectKeyRepeatOnce(1 /*repeatCount*/);
3868 // Stale key up from device 1.
3869 sendAndConsumeKeyUp(1 /* deviceId */);
3870 // Device 2 is still down, keep repeating
3871 expectKeyRepeatOnce(2 /*repeatCount*/);
3872 expectKeyRepeatOnce(3 /*repeatCount*/);
3873 // Device 2 key up
3874 sendAndConsumeKeyUp(2 /* deviceId */);
3875 mWindow->assertNoEvents();
3876}
3877
3878TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3879 sendAndConsumeKeyDown(1 /* deviceId */);
3880 expectKeyRepeatOnce(1 /*repeatCount*/);
3881 sendAndConsumeKeyDown(2 /* deviceId */);
3882 expectKeyRepeatOnce(1 /*repeatCount*/);
3883 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3884 sendAndConsumeKeyUp(2 /* deviceId */);
3885 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003886 mWindow->assertNoEvents();
3887}
3888
liushenxiang42232912021-05-21 20:24:09 +08003889TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3890 sendAndConsumeKeyDown(DEVICE_ID);
3891 expectKeyRepeatOnce(1 /*repeatCount*/);
3892 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3893 mDispatcher->notifyDeviceReset(&args);
3894 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3895 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3896 mWindow->assertNoEvents();
3897}
3898
Garfield Tan1c7bc862020-01-28 13:24:04 -08003899TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003900 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003901 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3902 InputEvent* repeatEvent = mWindow->consume();
3903 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3904 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3905 IdGenerator::getSource(repeatEvent->getId()));
3906 }
3907}
3908
3909TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003910 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003911
3912 std::unordered_set<int32_t> idSet;
3913 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3914 InputEvent* repeatEvent = mWindow->consume();
3915 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3916 int32_t id = repeatEvent->getId();
3917 EXPECT_EQ(idSet.end(), idSet.find(id));
3918 idSet.insert(id);
3919 }
3920}
3921
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003922/* Test InputDispatcher for MultiDisplay */
3923class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3924public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003925 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003926 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003927
Chris Yea209fde2020-07-22 13:54:51 -07003928 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003929 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003930 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003931
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003932 // Set focus window for primary display, but focused display would be second one.
3933 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003934 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003935 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003936 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003937 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003938
Chris Yea209fde2020-07-22 13:54:51 -07003939 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003940 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003941 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003942 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003943 // Set focus display to second one.
3944 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3945 // Set focus window for second display.
3946 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003947 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003948 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003949 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003950 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003951 }
3952
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003953 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003954 InputDispatcherTest::TearDown();
3955
Chris Yea209fde2020-07-22 13:54:51 -07003956 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003957 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003958 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003959 windowInSecondary.clear();
3960 }
3961
3962protected:
Chris Yea209fde2020-07-22 13:54:51 -07003963 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003964 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003965 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003966 sp<FakeWindowHandle> windowInSecondary;
3967};
3968
3969TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3970 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3972 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3973 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003974 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003975 windowInSecondary->assertNoEvents();
3976
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003977 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003978 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3979 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3980 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003981 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003982 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003983}
3984
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003985TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003986 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3988 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003989 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003990 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003991 windowInSecondary->assertNoEvents();
3992
3993 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003995 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003996 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003997 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003998
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003999 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004000 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08004001
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004002 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004003 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
4004 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08004005
4006 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004007 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004008 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08004009 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004010 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08004011 windowInSecondary->assertNoEvents();
4012}
4013
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004014// Test per-display input monitors for motion event.
4015TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08004016 FakeMonitorReceiver monitorInPrimary =
4017 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4018 FakeMonitorReceiver monitorInSecondary =
4019 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004020
4021 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4023 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004025 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08004026 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004027 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004028 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004029
4030 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4032 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4033 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004034 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004035 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004036 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004037 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004038
4039 // Test inject a non-pointer motion event.
4040 // If specific a display, it will dispatch to the focused window of particular display,
4041 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4043 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4044 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004045 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004046 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004047 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004048 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004049}
4050
4051// Test per-display input monitors for key event.
4052TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004053 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004054 FakeMonitorReceiver monitorInPrimary =
4055 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4056 FakeMonitorReceiver monitorInSecondary =
4057 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004058
4059 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4061 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004062 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004063 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004064 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004065 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004066}
4067
Vishnu Nair958da932020-08-21 17:12:37 -07004068TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4069 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004070 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004071 secondWindowInPrimary->setFocusable(true);
4072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4073 setFocusedWindow(secondWindowInPrimary);
4074 windowInPrimary->consumeFocusEvent(false);
4075 secondWindowInPrimary->consumeFocusEvent(true);
4076
4077 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4079 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004080 windowInPrimary->assertNoEvents();
4081 windowInSecondary->assertNoEvents();
4082 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4083}
4084
Arthur Hungdfd528e2021-12-08 13:23:04 +00004085TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4086 FakeMonitorReceiver monitorInPrimary =
4087 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4088 FakeMonitorReceiver monitorInSecondary =
4089 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4090
4091 // Test touch down on primary display.
4092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4093 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4095 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4096 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4097
4098 // Test touch down on second display.
4099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4100 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4101 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4102 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4103 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4104
4105 // Trigger cancel touch.
4106 mDispatcher->cancelCurrentTouch();
4107 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4108 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4109 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4110 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4111
4112 // Test inject a move motion event, no window/monitor should receive the event.
4113 ASSERT_EQ(InputEventInjectionResult::FAILED,
4114 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4115 ADISPLAY_ID_DEFAULT, {110, 200}))
4116 << "Inject motion event should return InputEventInjectionResult::FAILED";
4117 windowInPrimary->assertNoEvents();
4118 monitorInPrimary.assertNoEvents();
4119
4120 ASSERT_EQ(InputEventInjectionResult::FAILED,
4121 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4122 SECOND_DISPLAY_ID, {110, 200}))
4123 << "Inject motion event should return InputEventInjectionResult::FAILED";
4124 windowInSecondary->assertNoEvents();
4125 monitorInSecondary.assertNoEvents();
4126}
4127
Jackal Guof9696682018-10-05 12:23:23 +08004128class InputFilterTest : public InputDispatcherTest {
4129protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004130 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4131 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004132 NotifyMotionArgs motionArgs;
4133
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004134 motionArgs =
4135 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004136 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004137 motionArgs =
4138 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004139 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004140 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004141 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004142 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4143 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004144 } else {
4145 mFakePolicy->assertFilterInputEventWasNotCalled();
4146 }
4147 }
4148
4149 void testNotifyKey(bool expectToBeFiltered) {
4150 NotifyKeyArgs keyArgs;
4151
4152 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4153 mDispatcher->notifyKey(&keyArgs);
4154 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4155 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004156 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004157
4158 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004159 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004160 } else {
4161 mFakePolicy->assertFilterInputEventWasNotCalled();
4162 }
4163 }
4164};
4165
4166// Test InputFilter for MotionEvent
4167TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4168 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4169 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4170 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4171
4172 // Enable InputFilter
4173 mDispatcher->setInputFilterEnabled(true);
4174 // Test touch on both primary and second display, and check if both events are filtered.
4175 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4176 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4177
4178 // Disable InputFilter
4179 mDispatcher->setInputFilterEnabled(false);
4180 // Test touch on both primary and second display, and check if both events aren't filtered.
4181 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4182 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4183}
4184
4185// Test InputFilter for KeyEvent
4186TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4187 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4188 testNotifyKey(/*expectToBeFiltered*/ false);
4189
4190 // Enable InputFilter
4191 mDispatcher->setInputFilterEnabled(true);
4192 // Send a key event, and check if it is filtered.
4193 testNotifyKey(/*expectToBeFiltered*/ true);
4194
4195 // Disable InputFilter
4196 mDispatcher->setInputFilterEnabled(false);
4197 // Send a key event, and check if it isn't filtered.
4198 testNotifyKey(/*expectToBeFiltered*/ false);
4199}
4200
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004201// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4202// logical display coordinate space.
4203TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4204 ui::Transform firstDisplayTransform;
4205 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4206 ui::Transform secondDisplayTransform;
4207 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4208
4209 std::vector<gui::DisplayInfo> displayInfos(2);
4210 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4211 displayInfos[0].transform = firstDisplayTransform;
4212 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4213 displayInfos[1].transform = secondDisplayTransform;
4214
4215 mDispatcher->onWindowInfosChanged({}, displayInfos);
4216
4217 // Enable InputFilter
4218 mDispatcher->setInputFilterEnabled(true);
4219
4220 // Ensure the correct transforms are used for the displays.
4221 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4222 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4223}
4224
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004225class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4226protected:
4227 virtual void SetUp() override {
4228 InputDispatcherTest::SetUp();
4229
4230 /**
4231 * We don't need to enable input filter to test the injected event policy, but we enabled it
4232 * here to make the tests more realistic, since this policy only matters when inputfilter is
4233 * on.
4234 */
4235 mDispatcher->setInputFilterEnabled(true);
4236
4237 std::shared_ptr<InputApplicationHandle> application =
4238 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004239 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4240 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004241
4242 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4243 mWindow->setFocusable(true);
4244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4245 setFocusedWindow(mWindow);
4246 mWindow->consumeFocusEvent(true);
4247 }
4248
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004249 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4250 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004251 KeyEvent event;
4252
4253 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4254 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4255 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4256 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4257 const int32_t additionalPolicyFlags =
4258 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004260 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004261 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4262 policyFlags | additionalPolicyFlags));
4263
4264 InputEvent* received = mWindow->consume();
4265 ASSERT_NE(nullptr, received);
4266 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004267 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4268 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4269 ASSERT_EQ(flags, keyEvent.getFlags());
4270 }
4271
4272 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4273 int32_t flags) {
4274 MotionEvent event;
4275 PointerProperties pointerProperties[1];
4276 PointerCoords pointerCoords[1];
4277 pointerProperties[0].clear();
4278 pointerProperties[0].id = 0;
4279 pointerCoords[0].clear();
4280 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4281 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4282
4283 ui::Transform identityTransform;
4284 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4285 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4286 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4287 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4288 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004289 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004290 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004291 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4292
4293 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004295 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004296 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4297 policyFlags | additionalPolicyFlags));
4298
4299 InputEvent* received = mWindow->consume();
4300 ASSERT_NE(nullptr, received);
4301 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4302 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4303 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4304 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004305 }
4306
4307private:
4308 sp<FakeWindowHandle> mWindow;
4309};
4310
4311TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004312 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4313 // filter. Without it, the event will no different from a regularly injected event, and the
4314 // injected device id will be overwritten.
4315 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4316 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004317}
4318
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004319TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004320 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004321 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4322 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4323}
4324
4325TEST_F(InputFilterInjectionPolicyTest,
4326 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4327 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4328 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4329 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004330}
4331
4332TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4333 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004334 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004335}
4336
chaviwfd6d3512019-03-25 13:23:49 -07004337class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004338 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004339 InputDispatcherTest::SetUp();
4340
Chris Yea209fde2020-07-22 13:54:51 -07004341 std::shared_ptr<FakeApplicationHandle> application =
4342 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004343 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004344 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004345 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004346
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004347 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004348 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004349 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004350
4351 // Set focused application.
4352 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004353 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004354
4355 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004357 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004358 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004359 }
4360
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004361 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004362 InputDispatcherTest::TearDown();
4363
4364 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004365 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004366 }
4367
4368protected:
4369 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004370 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004371 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004372};
4373
4374// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4375// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4376// the onPointerDownOutsideFocus callback.
4377TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004379 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4380 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004382 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004383
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004384 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004385 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4386}
4387
4388// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4389// DOWN on the window that doesn't have focus. Ensure no window received the
4390// onPointerDownOutsideFocus callback.
4391TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004393 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004394 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004395 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004396
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004397 ASSERT_TRUE(mDispatcher->waitForIdle());
4398 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004399}
4400
4401// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4402// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4403TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4405 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004407 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004408
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004409 ASSERT_TRUE(mDispatcher->waitForIdle());
4410 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004411}
4412
4413// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4414// DOWN on the window that already has focus. Ensure no window received the
4415// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004416TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004417 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004418 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004419 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004420 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004421 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004422
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004423 ASSERT_TRUE(mDispatcher->waitForIdle());
4424 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004425}
4426
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004427// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4428// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4429TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4430 const MotionEvent event =
4431 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4432 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4433 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4434 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4435 .build();
4436 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4438 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4439
4440 ASSERT_TRUE(mDispatcher->waitForIdle());
4441 mFakePolicy->assertOnPointerDownWasNotCalled();
4442 // Ensure that the unfocused window did not receive any FOCUS events.
4443 mUnfocusedWindow->assertNoEvents();
4444}
4445
chaviwaf87b3e2019-10-01 16:59:28 -07004446// These tests ensures we can send touch events to a single client when there are multiple input
4447// windows that point to the same client token.
4448class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4449 virtual void SetUp() override {
4450 InputDispatcherTest::SetUp();
4451
Chris Yea209fde2020-07-22 13:54:51 -07004452 std::shared_ptr<FakeApplicationHandle> application =
4453 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004454 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4455 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004456 mWindow1->setFrame(Rect(0, 0, 100, 100));
4457
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004458 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4459 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004460 mWindow2->setFrame(Rect(100, 100, 200, 200));
4461
Arthur Hung72d8dc32020-03-28 00:48:39 +00004462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004463 }
4464
4465protected:
4466 sp<FakeWindowHandle> mWindow1;
4467 sp<FakeWindowHandle> mWindow2;
4468
4469 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004470 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004471 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4472 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004473 }
4474
4475 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4476 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004477 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004478 InputEvent* event = window->consume();
4479
4480 ASSERT_NE(nullptr, event) << name.c_str()
4481 << ": consumer should have returned non-NULL event.";
4482
4483 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4484 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4485 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4486
4487 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004488 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004489
4490 for (size_t i = 0; i < points.size(); i++) {
4491 float expectedX = points[i].x;
4492 float expectedY = points[i].y;
4493
4494 EXPECT_EQ(expectedX, motionEvent.getX(i))
4495 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4496 << ", got " << motionEvent.getX(i);
4497 EXPECT_EQ(expectedY, motionEvent.getY(i))
4498 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4499 << ", got " << motionEvent.getY(i);
4500 }
4501 }
chaviw9eaa22c2020-07-01 16:21:27 -07004502
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004503 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004504 std::vector<PointF> expectedPoints) {
4505 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4506 ADISPLAY_ID_DEFAULT, touchedPoints);
4507 mDispatcher->notifyMotion(&motionArgs);
4508
4509 // Always consume from window1 since it's the window that has the InputReceiver
4510 consumeMotionEvent(mWindow1, action, expectedPoints);
4511 }
chaviwaf87b3e2019-10-01 16:59:28 -07004512};
4513
4514TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4515 // Touch Window 1
4516 PointF touchedPoint = {10, 10};
4517 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004518 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004519
4520 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004521 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004522
4523 // Touch Window 2
4524 touchedPoint = {150, 150};
4525 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004526 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004527}
4528
chaviw9eaa22c2020-07-01 16:21:27 -07004529TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4530 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004531 mWindow2->setWindowScale(0.5f, 0.5f);
4532
4533 // Touch Window 1
4534 PointF touchedPoint = {10, 10};
4535 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004536 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004537 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004538 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004539
4540 // Touch Window 2
4541 touchedPoint = {150, 150};
4542 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004543 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4544 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004545
chaviw9eaa22c2020-07-01 16:21:27 -07004546 // Update the transform so rotation is set
4547 mWindow2->setWindowTransform(0, -1, 1, 0);
4548 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4549 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004550}
4551
chaviw9eaa22c2020-07-01 16:21:27 -07004552TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004553 mWindow2->setWindowScale(0.5f, 0.5f);
4554
4555 // Touch Window 1
4556 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4557 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004558 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004559
4560 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004561 touchedPoints.push_back(PointF{150, 150});
4562 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004563 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004564
chaviw9eaa22c2020-07-01 16:21:27 -07004565 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004566 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004567 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004568
chaviw9eaa22c2020-07-01 16:21:27 -07004569 // Update the transform so rotation is set for Window 2
4570 mWindow2->setWindowTransform(0, -1, 1, 0);
4571 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004572 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004573}
4574
chaviw9eaa22c2020-07-01 16:21:27 -07004575TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004576 mWindow2->setWindowScale(0.5f, 0.5f);
4577
4578 // Touch Window 1
4579 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4580 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004581 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004582
4583 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004584 touchedPoints.push_back(PointF{150, 150});
4585 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004586
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004587 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004588
4589 // Move both windows
4590 touchedPoints = {{20, 20}, {175, 175}};
4591 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4592 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4593
chaviw9eaa22c2020-07-01 16:21:27 -07004594 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004595
chaviw9eaa22c2020-07-01 16:21:27 -07004596 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004597 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004598 expectedPoints.pop_back();
4599
4600 // Touch Window 2
4601 mWindow2->setWindowTransform(0, -1, 1, 0);
4602 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004603 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004604
4605 // Move both windows
4606 touchedPoints = {{20, 20}, {175, 175}};
4607 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4608 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4609
4610 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004611}
4612
4613TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4614 mWindow1->setWindowScale(0.5f, 0.5f);
4615
4616 // Touch Window 1
4617 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4618 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004619 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004620
4621 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004622 touchedPoints.push_back(PointF{150, 150});
4623 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004624
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004625 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004626
4627 // Move both windows
4628 touchedPoints = {{20, 20}, {175, 175}};
4629 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4630 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4631
chaviw9eaa22c2020-07-01 16:21:27 -07004632 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004633}
4634
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004635class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4636 virtual void SetUp() override {
4637 InputDispatcherTest::SetUp();
4638
Chris Yea209fde2020-07-22 13:54:51 -07004639 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004640 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004641 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4642 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004643 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004644 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004645 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004646
4647 // Set focused application.
4648 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4649
4650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004651 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004652 mWindow->consumeFocusEvent(true);
4653 }
4654
4655 virtual void TearDown() override {
4656 InputDispatcherTest::TearDown();
4657 mWindow.clear();
4658 }
4659
4660protected:
Chris Yea209fde2020-07-22 13:54:51 -07004661 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004662 sp<FakeWindowHandle> mWindow;
4663 static constexpr PointF WINDOW_LOCATION = {20, 20};
4664
4665 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4668 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004670 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4671 WINDOW_LOCATION));
4672 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004673
4674 sp<FakeWindowHandle> addSpyWindow() {
4675 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004676 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004677 spy->setTrustedOverlay(true);
4678 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004679 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004680 spy->setDispatchingTimeout(30ms);
4681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4682 return spy;
4683 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004684};
4685
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004686// Send a tap and respond, which should not cause an ANR.
4687TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4688 tapOnWindow();
4689 mWindow->consumeMotionDown();
4690 mWindow->consumeMotionUp();
4691 ASSERT_TRUE(mDispatcher->waitForIdle());
4692 mFakePolicy->assertNotifyAnrWasNotCalled();
4693}
4694
4695// Send a regular key and respond, which should not cause an ANR.
4696TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4699 ASSERT_TRUE(mDispatcher->waitForIdle());
4700 mFakePolicy->assertNotifyAnrWasNotCalled();
4701}
4702
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004703TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4704 mWindow->setFocusable(false);
4705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4706 mWindow->consumeFocusEvent(false);
4707
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004709 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004710 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4711 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004712 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004713 // Key will not go to window because we have no focused window.
4714 // The 'no focused window' ANR timer should start instead.
4715
4716 // Now, the focused application goes away.
4717 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4718 // The key should get dropped and there should be no ANR.
4719
4720 ASSERT_TRUE(mDispatcher->waitForIdle());
4721 mFakePolicy->assertNotifyAnrWasNotCalled();
4722}
4723
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004724// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4726// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004727TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004729 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4730 WINDOW_LOCATION));
4731
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004732 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4733 ASSERT_TRUE(sequenceNum);
4734 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004735 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004737 mWindow->finishEvent(*sequenceNum);
4738 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4739 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004740 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004741 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004742}
4743
4744// Send a key to the app and have the app not respond right away.
4745TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4746 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004747 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004748 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4749 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004750 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004751 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004752 ASSERT_TRUE(mDispatcher->waitForIdle());
4753}
4754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755// We have a focused application, but no focused window
4756TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004757 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4759 mWindow->consumeFocusEvent(false);
4760
4761 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004762 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004763 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4764 WINDOW_LOCATION));
4765 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4766 mDispatcher->waitForIdle();
4767 mFakePolicy->assertNotifyAnrWasNotCalled();
4768
4769 // Once a focused event arrives, we get an ANR for this application
4770 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4771 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004772 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004774 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07004777 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004778 ASSERT_TRUE(mDispatcher->waitForIdle());
4779}
4780
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004781/**
4782 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4783 * there will not be an ANR.
4784 */
4785TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4786 mWindow->setFocusable(false);
4787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4788 mWindow->consumeFocusEvent(false);
4789
4790 KeyEvent event;
4791 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4792 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4793
4794 // Define a valid key down event that is stale (too old).
4795 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4796 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4797 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4798
4799 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4800
4801 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004802 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004803 InputEventInjectionSync::WAIT_FOR_RESULT,
4804 INJECT_EVENT_TIMEOUT, policyFlags);
4805 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4806 << "Injection should fail because the event is stale";
4807
4808 ASSERT_TRUE(mDispatcher->waitForIdle());
4809 mFakePolicy->assertNotifyAnrWasNotCalled();
4810 mWindow->assertNoEvents();
4811}
4812
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004814// Make sure that we don't notify policy twice about the same ANR.
4815TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004816 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4818 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004819
4820 // Once a focused event arrives, we get an ANR for this application
4821 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4822 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004823 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004825 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004826 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07004827 const std::chrono::duration appTimeout =
4828 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4829 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830
Vishnu Naire4df8752022-09-08 09:17:55 -07004831 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004832 // ANR should not be raised again. It is up to policy to do that if it desires.
4833 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004835 // If we now get a focused window, the ANR should stop, but the policy handles that via
4836 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 ASSERT_TRUE(mDispatcher->waitForIdle());
4838}
4839
4840// We have a focused application, but no focused window
4841TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004842 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4844 mWindow->consumeFocusEvent(false);
4845
4846 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4850 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004851
Vishnu Naire4df8752022-09-08 09:17:55 -07004852 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4853 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004854
4855 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004856 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 ASSERT_TRUE(mDispatcher->waitForIdle());
4858 mWindow->assertNoEvents();
4859}
4860
4861/**
4862 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4863 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4864 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4865 * the ANR mechanism should still work.
4866 *
4867 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4868 * DOWN event, while not responding on the second one.
4869 */
4870TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4871 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4872 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4873 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4874 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4875 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004876 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877
4878 // Now send ACTION_UP, with identical timestamp
4879 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4880 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4881 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4882 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884
4885 // We have now sent down and up. Let's consume first event and then ANR on the second.
4886 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4887 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004888 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889}
4890
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004891// A spy window can receive an ANR
4892TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4893 sp<FakeWindowHandle> spy = addSpyWindow();
4894
4895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4897 WINDOW_LOCATION));
4898 mWindow->consumeMotionDown();
4899
4900 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4901 ASSERT_TRUE(sequenceNum);
4902 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004903 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004904
4905 spy->finishEvent(*sequenceNum);
4906 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4907 0 /*flags*/);
4908 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004909 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004910}
4911
4912// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004914TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4915 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4918 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004921
4922 // Stuck on the ACTION_UP
4923 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004924 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004926 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004927 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004928 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4929 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930
4931 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4932 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004933 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004935 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004936}
4937
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004938// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004939// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004940TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4941 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004942
4943 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004944 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4945 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946
4947 mWindow->consumeMotionDown();
4948 // Stuck on the ACTION_UP
4949 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004950 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004952 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004953 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004954 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4955 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956
4957 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4958 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004959 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004961 spy->assertNoEvents();
4962}
4963
4964TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4965 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4966
4967 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4968
4969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4970 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4971 WINDOW_LOCATION));
4972
4973 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4974 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4975 ASSERT_TRUE(consumeSeq);
4976
Prabir Pradhanedd96402022-02-15 01:46:16 -08004977 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004978
4979 monitor.finishEvent(*consumeSeq);
4980 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4981
4982 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004983 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984}
4985
4986// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4987// process events, you don't get an anr. When the window later becomes unresponsive again, you
4988// get an ANR again.
4989// 1. tap -> block on ACTION_UP -> receive ANR
4990// 2. consume all pending events (= queue becomes healthy again)
4991// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4992TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4993 tapOnWindow();
4994
4995 mWindow->consumeMotionDown();
4996 // Block on ACTION_UP
4997 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004998 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999 mWindow->consumeMotionUp(); // Now the connection should be healthy again
5000 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005001 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002 mWindow->assertNoEvents();
5003
5004 tapOnWindow();
5005 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005006 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005007 mWindow->consumeMotionUp();
5008
5009 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005010 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005011 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012 mWindow->assertNoEvents();
5013}
5014
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005015// If a connection remains unresponsive for a while, make sure policy is only notified once about
5016// it.
5017TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005019 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5020 WINDOW_LOCATION));
5021
5022 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005023 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005025 // 'notifyConnectionUnresponsive' should only be called once per connection
5026 mFakePolicy->assertNotifyAnrWasNotCalled();
5027 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028 mWindow->consumeMotionDown();
5029 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
5030 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5031 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005032 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08005033 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005034 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005035}
5036
5037/**
5038 * If a window is processing a motion event, and then a key event comes in, the key event should
5039 * not to to the focused window until the motion is processed.
5040 *
5041 * Warning!!!
5042 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5043 * and the injection timeout that we specify when injecting the key.
5044 * We must have the injection timeout (10ms) be smaller than
5045 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5046 *
5047 * If that value changes, this test should also change.
5048 */
5049TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5050 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5052
5053 tapOnWindow();
5054 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5055 ASSERT_TRUE(downSequenceNum);
5056 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5057 ASSERT_TRUE(upSequenceNum);
5058 // Don't finish the events yet, and send a key
5059 // Injection will "succeed" because we will eventually give up and send the key to the focused
5060 // window even if motions are still being processed. But because the injection timeout is short,
5061 // we will receive INJECTION_TIMED_OUT as the result.
5062
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005063 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005064 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005065 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5066 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067 // Key will not be sent to the window, yet, because the window is still processing events
5068 // and the key remains pending, waiting for the touch events to be processed
5069 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5070 ASSERT_FALSE(keySequenceNum);
5071
5072 std::this_thread::sleep_for(500ms);
5073 // if we wait long enough though, dispatcher will give up, and still send the key
5074 // to the focused window, even though we have not yet finished the motion event
5075 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5076 mWindow->finishEvent(*downSequenceNum);
5077 mWindow->finishEvent(*upSequenceNum);
5078}
5079
5080/**
5081 * If a window is processing a motion event, and then a key event comes in, the key event should
5082 * not go to the focused window until the motion is processed.
5083 * If then a new motion comes in, then the pending key event should be going to the currently
5084 * focused window right away.
5085 */
5086TEST_F(InputDispatcherSingleWindowAnr,
5087 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5088 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5090
5091 tapOnWindow();
5092 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5093 ASSERT_TRUE(downSequenceNum);
5094 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5095 ASSERT_TRUE(upSequenceNum);
5096 // Don't finish the events yet, and send a key
5097 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005100 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005101 // At this point, key is still pending, and should not be sent to the application yet.
5102 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5103 ASSERT_FALSE(keySequenceNum);
5104
5105 // Now tap down again. It should cause the pending key to go to the focused window right away.
5106 tapOnWindow();
5107 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5108 // the other events yet. We can finish events in any order.
5109 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5110 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5111 mWindow->consumeMotionDown();
5112 mWindow->consumeMotionUp();
5113 mWindow->assertNoEvents();
5114}
5115
5116class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5117 virtual void SetUp() override {
5118 InputDispatcherTest::SetUp();
5119
Chris Yea209fde2020-07-22 13:54:51 -07005120 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005121 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005122 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5123 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005124 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005125 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005126 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005127
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005128 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5129 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005130 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132
5133 // Set focused application.
5134 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005135 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005136
5137 // Expect one focus window exist in display.
5138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005139 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 mFocusedWindow->consumeFocusEvent(true);
5141 }
5142
5143 virtual void TearDown() override {
5144 InputDispatcherTest::TearDown();
5145
5146 mUnfocusedWindow.clear();
5147 mFocusedWindow.clear();
5148 }
5149
5150protected:
Chris Yea209fde2020-07-22 13:54:51 -07005151 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152 sp<FakeWindowHandle> mUnfocusedWindow;
5153 sp<FakeWindowHandle> mFocusedWindow;
5154 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5155 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5156 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5157
5158 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5159
5160 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5161
5162private:
5163 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005165 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5166 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005168 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5169 location));
5170 }
5171};
5172
5173// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5174// should be ANR'd first.
5175TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005177 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5178 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005179 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005180 mFocusedWindow->consumeMotionDown();
5181 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5182 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5183 // We consumed all events, so no ANR
5184 ASSERT_TRUE(mDispatcher->waitForIdle());
5185 mFakePolicy->assertNotifyAnrWasNotCalled();
5186
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005188 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5189 FOCUSED_WINDOW_LOCATION));
5190 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5191 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005192
5193 const std::chrono::duration timeout =
5194 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005195 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005196 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5197 // sequence to make it consistent
5198 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005199 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005200 mFocusedWindow->consumeMotionDown();
5201 // This cancel is generated because the connection was unresponsive
5202 mFocusedWindow->consumeMotionCancel();
5203 mFocusedWindow->assertNoEvents();
5204 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005205 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005206 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5207 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005208 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005209}
5210
5211// If we have 2 windows with identical timeouts that are both unresponsive,
5212// it doesn't matter which order they should have ANR.
5213// But we should receive ANR for both.
5214TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5215 // Set the timeout for unfocused window to match the focused window
5216 mUnfocusedWindow->setDispatchingTimeout(10ms);
5217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5218
5219 tapOnFocusedWindow();
5220 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005221 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5222 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5223 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005224
5225 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005226 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5227 mFocusedWindow->getToken() == anrConnectionToken2);
5228 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5229 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005230
5231 ASSERT_TRUE(mDispatcher->waitForIdle());
5232 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005233
5234 mFocusedWindow->consumeMotionDown();
5235 mFocusedWindow->consumeMotionUp();
5236 mUnfocusedWindow->consumeMotionOutside();
5237
Prabir Pradhanedd96402022-02-15 01:46:16 -08005238 sp<IBinder> responsiveToken1, responsiveToken2;
5239 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5240 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005241
5242 // Both applications should be marked as responsive, in any order
5243 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5244 mFocusedWindow->getToken() == responsiveToken2);
5245 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5246 mUnfocusedWindow->getToken() == responsiveToken2);
5247 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005248}
5249
5250// If a window is already not responding, the second tap on the same window should be ignored.
5251// We should also log an error to account for the dropped event (not tested here).
5252// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5253TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5254 tapOnFocusedWindow();
5255 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5256 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5257 // Receive the events, but don't respond
5258 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5259 ASSERT_TRUE(downEventSequenceNum);
5260 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5261 ASSERT_TRUE(upEventSequenceNum);
5262 const std::chrono::duration timeout =
5263 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005264 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005265
5266 // Tap once again
5267 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005268 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5270 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005271 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005272 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5273 FOCUSED_WINDOW_LOCATION));
5274 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5275 // valid touch target
5276 mUnfocusedWindow->assertNoEvents();
5277
5278 // Consume the first tap
5279 mFocusedWindow->finishEvent(*downEventSequenceNum);
5280 mFocusedWindow->finishEvent(*upEventSequenceNum);
5281 ASSERT_TRUE(mDispatcher->waitForIdle());
5282 // The second tap did not go to the focused window
5283 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005284 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005285 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5286 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005287 mFakePolicy->assertNotifyAnrWasNotCalled();
5288}
5289
5290// If you tap outside of all windows, there will not be ANR
5291TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005292 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005293 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5294 LOCATION_OUTSIDE_ALL_WINDOWS));
5295 ASSERT_TRUE(mDispatcher->waitForIdle());
5296 mFakePolicy->assertNotifyAnrWasNotCalled();
5297}
5298
5299// Since the focused window is paused, tapping on it should not produce any events
5300TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5301 mFocusedWindow->setPaused(true);
5302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005305 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5306 FOCUSED_WINDOW_LOCATION));
5307
5308 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5309 ASSERT_TRUE(mDispatcher->waitForIdle());
5310 // Should not ANR because the window is paused, and touches shouldn't go to it
5311 mFakePolicy->assertNotifyAnrWasNotCalled();
5312
5313 mFocusedWindow->assertNoEvents();
5314 mUnfocusedWindow->assertNoEvents();
5315}
5316
5317/**
5318 * If a window is processing a motion event, and then a key event comes in, the key event should
5319 * not to to the focused window until the motion is processed.
5320 * If a different window becomes focused at this time, the key should go to that window instead.
5321 *
5322 * Warning!!!
5323 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5324 * and the injection timeout that we specify when injecting the key.
5325 * We must have the injection timeout (10ms) be smaller than
5326 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5327 *
5328 * If that value changes, this test should also change.
5329 */
5330TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5331 // Set a long ANR timeout to prevent it from triggering
5332 mFocusedWindow->setDispatchingTimeout(2s);
5333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5334
5335 tapOnUnfocusedWindow();
5336 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5337 ASSERT_TRUE(downSequenceNum);
5338 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5339 ASSERT_TRUE(upSequenceNum);
5340 // Don't finish the events yet, and send a key
5341 // Injection will succeed because we will eventually give up and send the key to the focused
5342 // window even if motions are still being processed.
5343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005344 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005345 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005346 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005348 // Key will not be sent to the window, yet, because the window is still processing events
5349 // and the key remains pending, waiting for the touch events to be processed
5350 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5351 ASSERT_FALSE(keySequenceNum);
5352
5353 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005354 mFocusedWindow->setFocusable(false);
5355 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005357 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358
5359 // Focus events should precede the key events
5360 mUnfocusedWindow->consumeFocusEvent(true);
5361 mFocusedWindow->consumeFocusEvent(false);
5362
5363 // Finish the tap events, which should unblock dispatcher
5364 mUnfocusedWindow->finishEvent(*downSequenceNum);
5365 mUnfocusedWindow->finishEvent(*upSequenceNum);
5366
5367 // Now that all queues are cleared and no backlog in the connections, the key event
5368 // can finally go to the newly focused "mUnfocusedWindow".
5369 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5370 mFocusedWindow->assertNoEvents();
5371 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005372 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005373}
5374
5375// When the touch stream is split across 2 windows, and one of them does not respond,
5376// then ANR should be raised and the touch should be canceled for the unresponsive window.
5377// The other window should not be affected by that.
5378TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5379 // Touch Window 1
5380 NotifyMotionArgs motionArgs =
5381 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5382 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5383 mDispatcher->notifyMotion(&motionArgs);
5384 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5385 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5386
5387 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005388 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5389 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005390 mDispatcher->notifyMotion(&motionArgs);
5391
5392 const std::chrono::duration timeout =
5393 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005394 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005395
5396 mUnfocusedWindow->consumeMotionDown();
5397 mFocusedWindow->consumeMotionDown();
5398 // Focused window may or may not receive ACTION_MOVE
5399 // But it should definitely receive ACTION_CANCEL due to the ANR
5400 InputEvent* event;
5401 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5402 ASSERT_TRUE(moveOrCancelSequenceNum);
5403 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5404 ASSERT_NE(nullptr, event);
5405 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5406 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5407 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5408 mFocusedWindow->consumeMotionCancel();
5409 } else {
5410 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5411 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005412 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005413 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5414 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005415
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005416 mUnfocusedWindow->assertNoEvents();
5417 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005418 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005419}
5420
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005421/**
5422 * If we have no focused window, and a key comes in, we start the ANR timer.
5423 * The focused application should add a focused window before the timer runs out to prevent ANR.
5424 *
5425 * If the user touches another application during this time, the key should be dropped.
5426 * Next, if a new focused window comes in, without toggling the focused application,
5427 * then no ANR should occur.
5428 *
5429 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5430 * but in some cases the policy may not update the focused application.
5431 */
5432TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5433 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5434 std::make_shared<FakeApplicationHandle>();
5435 focusedApplication->setDispatchingTimeout(60ms);
5436 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5437 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5438 mFocusedWindow->setFocusable(false);
5439
5440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5441 mFocusedWindow->consumeFocusEvent(false);
5442
5443 // Send a key. The ANR timer should start because there is no focused window.
5444 // 'focusedApplication' will get blamed if this timer completes.
5445 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005446 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005447 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005448 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5449 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005451
5452 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5453 // then the injected touches won't cause the focused event to get dropped.
5454 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5455 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5456 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5457 // For this test, it means that the key would get delivered to the window once it becomes
5458 // focused.
5459 std::this_thread::sleep_for(10ms);
5460
5461 // Touch unfocused window. This should force the pending key to get dropped.
5462 NotifyMotionArgs motionArgs =
5463 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5464 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5465 mDispatcher->notifyMotion(&motionArgs);
5466
5467 // We do not consume the motion right away, because that would require dispatcher to first
5468 // process (== drop) the key event, and by that time, ANR will be raised.
5469 // Set the focused window first.
5470 mFocusedWindow->setFocusable(true);
5471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5472 setFocusedWindow(mFocusedWindow);
5473 mFocusedWindow->consumeFocusEvent(true);
5474 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5475 // to another application. This could be a bug / behaviour in the policy.
5476
5477 mUnfocusedWindow->consumeMotionDown();
5478
5479 ASSERT_TRUE(mDispatcher->waitForIdle());
5480 // Should not ANR because we actually have a focused window. It was just added too slowly.
5481 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5482}
5483
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005484// These tests ensure we cannot send touch events to a window that's positioned behind a window
5485// that has feature NO_INPUT_CHANNEL.
5486// Layout:
5487// Top (closest to user)
5488// mNoInputWindow (above all windows)
5489// mBottomWindow
5490// Bottom (furthest from user)
5491class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5492 virtual void SetUp() override {
5493 InputDispatcherTest::SetUp();
5494
5495 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005496 mNoInputWindow =
5497 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5498 "Window without input channel", ADISPLAY_ID_DEFAULT,
5499 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005500 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005501 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5502 // It's perfectly valid for this window to not have an associated input channel
5503
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005504 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5505 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005506 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5507
5508 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5509 }
5510
5511protected:
5512 std::shared_ptr<FakeApplicationHandle> mApplication;
5513 sp<FakeWindowHandle> mNoInputWindow;
5514 sp<FakeWindowHandle> mBottomWindow;
5515};
5516
5517TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5518 PointF touchedPoint = {10, 10};
5519
5520 NotifyMotionArgs motionArgs =
5521 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5522 ADISPLAY_ID_DEFAULT, {touchedPoint});
5523 mDispatcher->notifyMotion(&motionArgs);
5524
5525 mNoInputWindow->assertNoEvents();
5526 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5527 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5528 // and therefore should prevent mBottomWindow from receiving touches
5529 mBottomWindow->assertNoEvents();
5530}
5531
5532/**
5533 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5534 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5535 */
5536TEST_F(InputDispatcherMultiWindowOcclusionTests,
5537 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005538 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5539 "Window with input channel and NO_INPUT_CHANNEL",
5540 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005541
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005542 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005543 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5545
5546 PointF touchedPoint = {10, 10};
5547
5548 NotifyMotionArgs motionArgs =
5549 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5550 ADISPLAY_ID_DEFAULT, {touchedPoint});
5551 mDispatcher->notifyMotion(&motionArgs);
5552
5553 mNoInputWindow->assertNoEvents();
5554 mBottomWindow->assertNoEvents();
5555}
5556
Vishnu Nair958da932020-08-21 17:12:37 -07005557class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5558protected:
5559 std::shared_ptr<FakeApplicationHandle> mApp;
5560 sp<FakeWindowHandle> mWindow;
5561 sp<FakeWindowHandle> mMirror;
5562
5563 virtual void SetUp() override {
5564 InputDispatcherTest::SetUp();
5565 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005566 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5567 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5568 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005569 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5570 mWindow->setFocusable(true);
5571 mMirror->setFocusable(true);
5572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5573 }
5574};
5575
5576TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5577 // Request focus on a mirrored window
5578 setFocusedWindow(mMirror);
5579
5580 // window gets focused
5581 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5583 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005584 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5585}
5586
5587// A focused & mirrored window remains focused only if the window and its mirror are both
5588// focusable.
5589TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5590 setFocusedWindow(mMirror);
5591
5592 // window gets focused
5593 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5595 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005596 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5598 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005599 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5600
5601 mMirror->setFocusable(false);
5602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5603
5604 // window loses focus since one of the windows associated with the token in not focusable
5605 mWindow->consumeFocusEvent(false);
5606
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5608 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005609 mWindow->assertNoEvents();
5610}
5611
5612// A focused & mirrored window remains focused until the window and its mirror both become
5613// invisible.
5614TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5615 setFocusedWindow(mMirror);
5616
5617 // window gets focused
5618 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5620 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005621 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5623 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005624 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5625
5626 mMirror->setVisible(false);
5627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5628
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5630 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005631 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5633 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005634 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5635
5636 mWindow->setVisible(false);
5637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5638
5639 // window loses focus only after all windows associated with the token become invisible.
5640 mWindow->consumeFocusEvent(false);
5641
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005642 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5643 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005644 mWindow->assertNoEvents();
5645}
5646
5647// A focused & mirrored window remains focused until both windows are removed.
5648TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5649 setFocusedWindow(mMirror);
5650
5651 // window gets focused
5652 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5654 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005655 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005656 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5657 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005658 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5659
5660 // single window is removed but the window token remains focused
5661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5662
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5664 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005665 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5667 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005668 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5669
5670 // Both windows are removed
5671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5672 mWindow->consumeFocusEvent(false);
5673
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005674 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5675 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005676 mWindow->assertNoEvents();
5677}
5678
5679// Focus request can be pending until one window becomes visible.
5680TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5681 // Request focus on an invisible mirror.
5682 mWindow->setVisible(false);
5683 mMirror->setVisible(false);
5684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5685 setFocusedWindow(mMirror);
5686
5687 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005689 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005690 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005691
5692 mMirror->setVisible(true);
5693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5694
5695 // window gets focused
5696 mWindow->consumeFocusEvent(true);
5697 // window gets the pending key event
5698 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5699}
Prabir Pradhan99987712020-11-10 18:43:05 -08005700
5701class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5702protected:
5703 std::shared_ptr<FakeApplicationHandle> mApp;
5704 sp<FakeWindowHandle> mWindow;
5705 sp<FakeWindowHandle> mSecondWindow;
5706
5707 void SetUp() override {
5708 InputDispatcherTest::SetUp();
5709 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005710 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005711 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005712 mSecondWindow =
5713 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005714 mSecondWindow->setFocusable(true);
5715
5716 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5718
5719 setFocusedWindow(mWindow);
5720 mWindow->consumeFocusEvent(true);
5721 }
5722
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005723 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5724 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005725 mDispatcher->notifyPointerCaptureChanged(&args);
5726 }
5727
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005728 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5729 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005730 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005731 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5732 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005733 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005734 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005735 }
5736};
5737
5738TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5739 // Ensure that capture cannot be obtained for unfocused windows.
5740 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5741 mFakePolicy->assertSetPointerCaptureNotCalled();
5742 mSecondWindow->assertNoEvents();
5743
5744 // Ensure that capture can be enabled from the focus window.
5745 requestAndVerifyPointerCapture(mWindow, true);
5746
5747 // Ensure that capture cannot be disabled from a window that does not have capture.
5748 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5749 mFakePolicy->assertSetPointerCaptureNotCalled();
5750
5751 // Ensure that capture can be disabled from the window with capture.
5752 requestAndVerifyPointerCapture(mWindow, false);
5753}
5754
5755TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005756 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005757
5758 setFocusedWindow(mSecondWindow);
5759
5760 // Ensure that the capture disabled event was sent first.
5761 mWindow->consumeCaptureEvent(false);
5762 mWindow->consumeFocusEvent(false);
5763 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005764 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005765
5766 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005767 notifyPointerCaptureChanged({});
5768 notifyPointerCaptureChanged(request);
5769 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005770 mWindow->assertNoEvents();
5771 mSecondWindow->assertNoEvents();
5772 mFakePolicy->assertSetPointerCaptureNotCalled();
5773}
5774
5775TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005776 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005777
5778 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005779 notifyPointerCaptureChanged({});
5780 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005781
5782 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005783 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005784 mWindow->consumeCaptureEvent(false);
5785 mWindow->assertNoEvents();
5786}
5787
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005788TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5789 requestAndVerifyPointerCapture(mWindow, true);
5790
5791 // The first window loses focus.
5792 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005793 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005794 mWindow->consumeCaptureEvent(false);
5795
5796 // Request Pointer Capture from the second window before the notification from InputReader
5797 // arrives.
5798 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005799 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005800
5801 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005802 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005803
5804 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005805 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005806
5807 mSecondWindow->consumeFocusEvent(true);
5808 mSecondWindow->consumeCaptureEvent(true);
5809}
5810
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005811TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5812 // App repeatedly enables and disables capture.
5813 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5814 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5815 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5816 mFakePolicy->assertSetPointerCaptureCalled(false);
5817 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5818 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5819
5820 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5821 // first request is now stale, this should do nothing.
5822 notifyPointerCaptureChanged(firstRequest);
5823 mWindow->assertNoEvents();
5824
5825 // InputReader notifies that the second request was enabled.
5826 notifyPointerCaptureChanged(secondRequest);
5827 mWindow->consumeCaptureEvent(true);
5828}
5829
Prabir Pradhan7092e262022-05-03 16:51:09 +00005830TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5831 requestAndVerifyPointerCapture(mWindow, true);
5832
5833 // App toggles pointer capture off and on.
5834 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5835 mFakePolicy->assertSetPointerCaptureCalled(false);
5836
5837 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5838 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5839
5840 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5841 // preceding "disable" request.
5842 notifyPointerCaptureChanged(enableRequest);
5843
5844 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5845 // any notifications.
5846 mWindow->assertNoEvents();
5847}
5848
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005849class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5850protected:
5851 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005852
5853 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5854 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5855
5856 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5857 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5858
5859 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5860 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5861 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5862 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5863 MAXIMUM_OBSCURING_OPACITY);
5864
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005865 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005866 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005867 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005868
5869 sp<FakeWindowHandle> mTouchWindow;
5870
5871 virtual void SetUp() override {
5872 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005873 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005874 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5875 }
5876
5877 virtual void TearDown() override {
5878 InputDispatcherTest::TearDown();
5879 mTouchWindow.clear();
5880 }
5881
chaviw3277faf2021-05-19 16:45:23 -05005882 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5883 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005884 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005885 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005886 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005887 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005888 return window;
5889 }
5890
5891 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5892 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5893 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005894 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005895 // Generate an arbitrary PID based on the UID
5896 window->setOwnerInfo(1777 + (uid % 10000), uid);
5897 return window;
5898 }
5899
5900 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5901 NotifyMotionArgs args =
5902 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5903 ADISPLAY_ID_DEFAULT, points);
5904 mDispatcher->notifyMotion(&args);
5905 }
5906};
5907
5908TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005909 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005910 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005912
5913 touch();
5914
5915 mTouchWindow->assertNoEvents();
5916}
5917
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005918TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005919 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5920 const sp<FakeWindowHandle>& w =
5921 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5923
5924 touch();
5925
5926 mTouchWindow->assertNoEvents();
5927}
5928
5929TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005930 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5931 const sp<FakeWindowHandle>& w =
5932 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5934
5935 touch();
5936
5937 w->assertNoEvents();
5938}
5939
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005940TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005941 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005943
5944 touch();
5945
5946 mTouchWindow->consumeAnyMotionDown();
5947}
5948
5949TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005950 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005951 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005952 w->setFrame(Rect(0, 0, 50, 50));
5953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005954
5955 touch({PointF{100, 100}});
5956
5957 mTouchWindow->consumeAnyMotionDown();
5958}
5959
5960TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005961 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005962 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5964
5965 touch();
5966
5967 mTouchWindow->consumeAnyMotionDown();
5968}
5969
5970TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5971 const sp<FakeWindowHandle>& w =
5972 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005974
5975 touch();
5976
5977 mTouchWindow->consumeAnyMotionDown();
5978}
5979
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005980TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5981 const sp<FakeWindowHandle>& w =
5982 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5984
5985 touch();
5986
5987 w->assertNoEvents();
5988}
5989
5990/**
5991 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5992 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5993 * window, the occluding window will still receive ACTION_OUTSIDE event.
5994 */
5995TEST_F(InputDispatcherUntrustedTouchesTest,
5996 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5997 const sp<FakeWindowHandle>& w =
5998 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005999 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6001
6002 touch();
6003
6004 w->consumeMotionOutside();
6005}
6006
6007TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
6008 const sp<FakeWindowHandle>& w =
6009 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006010 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6012
6013 touch();
6014
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006015 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00006016}
6017
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006018TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006019 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006020 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6021 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6023
6024 touch();
6025
6026 mTouchWindow->consumeAnyMotionDown();
6027}
6028
6029TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
6030 const sp<FakeWindowHandle>& w =
6031 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6032 MAXIMUM_OBSCURING_OPACITY);
6033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006034
6035 touch();
6036
6037 mTouchWindow->consumeAnyMotionDown();
6038}
6039
6040TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006041 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006042 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6043 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6045
6046 touch();
6047
6048 mTouchWindow->assertNoEvents();
6049}
6050
6051TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6052 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6053 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006054 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6055 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006056 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006057 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6058 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6060
6061 touch();
6062
6063 mTouchWindow->assertNoEvents();
6064}
6065
6066TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6067 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6068 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006069 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6070 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006071 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006072 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6073 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6075
6076 touch();
6077
6078 mTouchWindow->consumeAnyMotionDown();
6079}
6080
6081TEST_F(InputDispatcherUntrustedTouchesTest,
6082 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6083 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006084 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6085 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006086 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006087 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6088 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006089 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6090
6091 touch();
6092
6093 mTouchWindow->consumeAnyMotionDown();
6094}
6095
6096TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6097 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006098 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6099 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006100 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006101 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6102 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006104
6105 touch();
6106
6107 mTouchWindow->assertNoEvents();
6108}
6109
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006110TEST_F(InputDispatcherUntrustedTouchesTest,
6111 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6112 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006113 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6114 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006115 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006116 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6117 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6119
6120 touch();
6121
6122 mTouchWindow->assertNoEvents();
6123}
6124
6125TEST_F(InputDispatcherUntrustedTouchesTest,
6126 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6127 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006128 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6129 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006130 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006131 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6132 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6134
6135 touch();
6136
6137 mTouchWindow->consumeAnyMotionDown();
6138}
6139
6140TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6141 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006142 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6143 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6145
6146 touch();
6147
6148 mTouchWindow->consumeAnyMotionDown();
6149}
6150
6151TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6152 const sp<FakeWindowHandle>& w =
6153 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6155
6156 touch();
6157
6158 mTouchWindow->consumeAnyMotionDown();
6159}
6160
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006161TEST_F(InputDispatcherUntrustedTouchesTest,
6162 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6163 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6164 const sp<FakeWindowHandle>& w =
6165 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6166 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6167
6168 touch();
6169
6170 mTouchWindow->assertNoEvents();
6171}
6172
6173TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6174 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6175 const sp<FakeWindowHandle>& w =
6176 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6178
6179 touch();
6180
6181 mTouchWindow->consumeAnyMotionDown();
6182}
6183
6184TEST_F(InputDispatcherUntrustedTouchesTest,
6185 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6186 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6187 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006188 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6189 OPACITY_ABOVE_THRESHOLD);
6190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6191
6192 touch();
6193
6194 mTouchWindow->consumeAnyMotionDown();
6195}
6196
6197TEST_F(InputDispatcherUntrustedTouchesTest,
6198 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6199 const sp<FakeWindowHandle>& w1 =
6200 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6201 OPACITY_BELOW_THRESHOLD);
6202 const sp<FakeWindowHandle>& w2 =
6203 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6204 OPACITY_BELOW_THRESHOLD);
6205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6206
6207 touch();
6208
6209 mTouchWindow->assertNoEvents();
6210}
6211
6212/**
6213 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6214 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6215 * (which alone would result in allowing touches) does not affect the blocking behavior.
6216 */
6217TEST_F(InputDispatcherUntrustedTouchesTest,
6218 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6219 const sp<FakeWindowHandle>& wB =
6220 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6221 OPACITY_BELOW_THRESHOLD);
6222 const sp<FakeWindowHandle>& wC =
6223 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6224 OPACITY_BELOW_THRESHOLD);
6225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6226
6227 touch();
6228
6229 mTouchWindow->assertNoEvents();
6230}
6231
6232/**
6233 * This test is testing that a window from a different UID but with same application token doesn't
6234 * block the touch. Apps can share the application token for close UI collaboration for example.
6235 */
6236TEST_F(InputDispatcherUntrustedTouchesTest,
6237 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6238 const sp<FakeWindowHandle>& w =
6239 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6240 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6242
6243 touch();
6244
6245 mTouchWindow->consumeAnyMotionDown();
6246}
6247
arthurhungb89ccb02020-12-30 16:19:01 +08006248class InputDispatcherDragTests : public InputDispatcherTest {
6249protected:
6250 std::shared_ptr<FakeApplicationHandle> mApp;
6251 sp<FakeWindowHandle> mWindow;
6252 sp<FakeWindowHandle> mSecondWindow;
6253 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006254 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006255 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6256 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006257
6258 void SetUp() override {
6259 InputDispatcherTest::SetUp();
6260 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006261 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006262 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006263
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006264 mSecondWindow =
6265 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006266 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006267
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006268 mSpyWindow =
6269 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006270 mSpyWindow->setSpy(true);
6271 mSpyWindow->setTrustedOverlay(true);
6272 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6273
arthurhungb89ccb02020-12-30 16:19:01 +08006274 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006275 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006276 }
6277
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006278 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6279 switch (fromSource) {
6280 case AINPUT_SOURCE_TOUCHSCREEN:
6281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6282 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6283 ADISPLAY_ID_DEFAULT, {50, 50}))
6284 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6285 break;
6286 case AINPUT_SOURCE_STYLUS:
6287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6288 injectMotionEvent(
6289 mDispatcher,
6290 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6291 AINPUT_SOURCE_STYLUS)
6292 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6293 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6294 .x(50)
6295 .y(50))
6296 .build()));
6297 break;
6298 case AINPUT_SOURCE_MOUSE:
6299 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6300 injectMotionEvent(
6301 mDispatcher,
6302 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6303 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6304 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6305 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6306 .x(50)
6307 .y(50))
6308 .build()));
6309 break;
6310 default:
6311 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6312 }
arthurhungb89ccb02020-12-30 16:19:01 +08006313
6314 // Window should receive motion event.
6315 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006316 // Spy window should also receive motion event
6317 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006318 }
6319
6320 // Start performing drag, we will create a drag window and transfer touch to it.
6321 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6322 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006323 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006324 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006325 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006326 }
arthurhungb89ccb02020-12-30 16:19:01 +08006327
6328 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006329 mDragWindow =
6330 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006331 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006332 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006333 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006334
6335 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006336 bool transferred =
6337 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6338 true /* isDragDrop */);
6339 if (transferred) {
6340 mWindow->consumeMotionCancel();
6341 mDragWindow->consumeMotionDown();
6342 }
6343 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006344 }
6345};
6346
6347TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006348 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006349
6350 // Move on window.
6351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6352 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6353 ADISPLAY_ID_DEFAULT, {50, 50}))
6354 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6355 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6356 mWindow->consumeDragEvent(false, 50, 50);
6357 mSecondWindow->assertNoEvents();
6358
6359 // Move to another window.
6360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6361 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6362 ADISPLAY_ID_DEFAULT, {150, 50}))
6363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6364 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6365 mWindow->consumeDragEvent(true, 150, 50);
6366 mSecondWindow->consumeDragEvent(false, 50, 50);
6367
6368 // Move back to original window.
6369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6370 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6371 ADISPLAY_ID_DEFAULT, {50, 50}))
6372 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6373 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6374 mWindow->consumeDragEvent(false, 50, 50);
6375 mSecondWindow->consumeDragEvent(true, -50, 50);
6376
6377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6378 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6379 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6380 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6381 mWindow->assertNoEvents();
6382 mSecondWindow->assertNoEvents();
6383}
6384
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006385TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006386 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006387
6388 // No cancel event after drag start
6389 mSpyWindow->assertNoEvents();
6390
6391 const MotionEvent secondFingerDownEvent =
6392 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6393 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6394 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6395 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6396 .build();
6397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6398 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6399 InputEventInjectionSync::WAIT_FOR_RESULT))
6400 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6401
6402 // Receives cancel for first pointer after next pointer down
6403 mSpyWindow->consumeMotionCancel();
6404 mSpyWindow->consumeMotionDown();
6405
6406 mSpyWindow->assertNoEvents();
6407}
6408
arthurhungf452d0b2021-01-06 00:19:52 +08006409TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006410 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006411
6412 // Move on window.
6413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6414 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6415 ADISPLAY_ID_DEFAULT, {50, 50}))
6416 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6417 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6418 mWindow->consumeDragEvent(false, 50, 50);
6419 mSecondWindow->assertNoEvents();
6420
6421 // Move to another window.
6422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6423 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6424 ADISPLAY_ID_DEFAULT, {150, 50}))
6425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6426 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6427 mWindow->consumeDragEvent(true, 150, 50);
6428 mSecondWindow->consumeDragEvent(false, 50, 50);
6429
6430 // drop to another window.
6431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6432 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6433 {150, 50}))
6434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6435 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6436 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6437 mWindow->assertNoEvents();
6438 mSecondWindow->assertNoEvents();
6439}
6440
arthurhung6d4bed92021-03-17 11:59:33 +08006441TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006442 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006443
6444 // Move on window and keep button pressed.
6445 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6446 injectMotionEvent(mDispatcher,
6447 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6448 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6449 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6450 .x(50)
6451 .y(50))
6452 .build()))
6453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6454 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6455 mWindow->consumeDragEvent(false, 50, 50);
6456 mSecondWindow->assertNoEvents();
6457
6458 // Move to another window and release button, expect to drop item.
6459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6460 injectMotionEvent(mDispatcher,
6461 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6462 .buttonState(0)
6463 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6464 .x(150)
6465 .y(50))
6466 .build()))
6467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6468 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6469 mWindow->assertNoEvents();
6470 mSecondWindow->assertNoEvents();
6471 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6472
6473 // nothing to the window.
6474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6475 injectMotionEvent(mDispatcher,
6476 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6477 .buttonState(0)
6478 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6479 .x(150)
6480 .y(50))
6481 .build()))
6482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6483 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6484 mWindow->assertNoEvents();
6485 mSecondWindow->assertNoEvents();
6486}
6487
Arthur Hung54745652022-04-20 07:17:41 +00006488TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006489 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006490
6491 // Set second window invisible.
6492 mSecondWindow->setVisible(false);
6493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6494
6495 // Move on window.
6496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6497 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6498 ADISPLAY_ID_DEFAULT, {50, 50}))
6499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6500 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6501 mWindow->consumeDragEvent(false, 50, 50);
6502 mSecondWindow->assertNoEvents();
6503
6504 // Move to another window.
6505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6506 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6507 ADISPLAY_ID_DEFAULT, {150, 50}))
6508 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6509 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6510 mWindow->consumeDragEvent(true, 150, 50);
6511 mSecondWindow->assertNoEvents();
6512
6513 // drop to another window.
6514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6515 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6516 {150, 50}))
6517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6518 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6519 mFakePolicy->assertDropTargetEquals(nullptr);
6520 mWindow->assertNoEvents();
6521 mSecondWindow->assertNoEvents();
6522}
6523
Arthur Hung54745652022-04-20 07:17:41 +00006524TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006525 // Ensure window could track pointerIds if it didn't support split touch.
6526 mWindow->setPreventSplitting(true);
6527
Arthur Hung54745652022-04-20 07:17:41 +00006528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6529 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6530 {50, 50}))
6531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6532 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6533
6534 const MotionEvent secondFingerDownEvent =
6535 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6536 .displayId(ADISPLAY_ID_DEFAULT)
6537 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6538 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6539 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6540 .build();
6541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6542 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6543 InputEventInjectionSync::WAIT_FOR_RESULT))
6544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6545 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6546
6547 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006548 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006549}
6550
6551TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6552 // First down on second window.
6553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6555 {150, 50}))
6556 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6557
6558 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6559
6560 // Second down on first window.
6561 const MotionEvent secondFingerDownEvent =
6562 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6563 .displayId(ADISPLAY_ID_DEFAULT)
6564 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6565 .pointer(
6566 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6567 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6568 .build();
6569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6570 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6571 InputEventInjectionSync::WAIT_FOR_RESULT))
6572 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6573 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6574
6575 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006576 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006577
6578 // Move on window.
6579 const MotionEvent secondFingerMoveEvent =
6580 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6581 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6582 .pointer(
6583 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6584 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6585 .build();
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6588 InputEventInjectionSync::WAIT_FOR_RESULT));
6589 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6590 mWindow->consumeDragEvent(false, 50, 50);
6591 mSecondWindow->consumeMotionMove();
6592
6593 // Release the drag pointer should perform drop.
6594 const MotionEvent secondFingerUpEvent =
6595 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6596 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6597 .pointer(
6598 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6599 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6600 .build();
6601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6602 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6603 InputEventInjectionSync::WAIT_FOR_RESULT));
6604 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6605 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6606 mWindow->assertNoEvents();
6607 mSecondWindow->consumeMotionMove();
6608}
6609
Arthur Hung3915c1f2022-05-31 07:17:17 +00006610TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006611 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006612
6613 // Update window of second display.
6614 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006615 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006616 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6617
6618 // Let second display has a touch state.
6619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6620 injectMotionEvent(mDispatcher,
6621 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6622 AINPUT_SOURCE_TOUCHSCREEN)
6623 .displayId(SECOND_DISPLAY_ID)
6624 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6625 .x(100)
6626 .y(100))
6627 .build()));
6628 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6629 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6630 // Update window again.
6631 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6632
6633 // Move on window.
6634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6635 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6636 ADISPLAY_ID_DEFAULT, {50, 50}))
6637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6638 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6639 mWindow->consumeDragEvent(false, 50, 50);
6640 mSecondWindow->assertNoEvents();
6641
6642 // Move to another window.
6643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6644 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6645 ADISPLAY_ID_DEFAULT, {150, 50}))
6646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6647 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6648 mWindow->consumeDragEvent(true, 150, 50);
6649 mSecondWindow->consumeDragEvent(false, 50, 50);
6650
6651 // drop to another window.
6652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6653 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6654 {150, 50}))
6655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6656 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6657 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6658 mWindow->assertNoEvents();
6659 mSecondWindow->assertNoEvents();
6660}
6661
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006662TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6663 startDrag(true, AINPUT_SOURCE_MOUSE);
6664 // Move on window.
6665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6666 injectMotionEvent(mDispatcher,
6667 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6668 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6669 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6670 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6671 .x(50)
6672 .y(50))
6673 .build()))
6674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6675 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6676 mWindow->consumeDragEvent(false, 50, 50);
6677 mSecondWindow->assertNoEvents();
6678
6679 // Move to another window.
6680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6681 injectMotionEvent(mDispatcher,
6682 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6683 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6684 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6685 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6686 .x(150)
6687 .y(50))
6688 .build()))
6689 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6690 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6691 mWindow->consumeDragEvent(true, 150, 50);
6692 mSecondWindow->consumeDragEvent(false, 50, 50);
6693
6694 // drop to another window.
6695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6696 injectMotionEvent(mDispatcher,
6697 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6698 .buttonState(0)
6699 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6700 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6701 .x(150)
6702 .y(50))
6703 .build()))
6704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6705 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6706 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6707 mWindow->assertNoEvents();
6708 mSecondWindow->assertNoEvents();
6709}
6710
Vishnu Nair062a8672021-09-03 16:07:44 -07006711class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6712
6713TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6714 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006715 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6716 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006717 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006718 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6719 window->setFocusable(true);
6720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6721 setFocusedWindow(window);
6722 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6723
6724 // With the flag set, window should not get any input
6725 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6726 mDispatcher->notifyKey(&keyArgs);
6727 window->assertNoEvents();
6728
6729 NotifyMotionArgs motionArgs =
6730 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6731 ADISPLAY_ID_DEFAULT);
6732 mDispatcher->notifyMotion(&motionArgs);
6733 window->assertNoEvents();
6734
6735 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006736 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6738
6739 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6740 mDispatcher->notifyKey(&keyArgs);
6741 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6742
6743 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6744 ADISPLAY_ID_DEFAULT);
6745 mDispatcher->notifyMotion(&motionArgs);
6746 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6747 window->assertNoEvents();
6748}
6749
6750TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6751 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6752 std::make_shared<FakeApplicationHandle>();
6753 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006754 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6755 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006756 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6757 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006758 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006759 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006760 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6761 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006762 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006763 window->setOwnerInfo(222, 222);
6764 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6765 window->setFocusable(true);
6766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6767 setFocusedWindow(window);
6768 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6769
6770 // With the flag set, window should not get any input
6771 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6772 mDispatcher->notifyKey(&keyArgs);
6773 window->assertNoEvents();
6774
6775 NotifyMotionArgs motionArgs =
6776 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6777 ADISPLAY_ID_DEFAULT);
6778 mDispatcher->notifyMotion(&motionArgs);
6779 window->assertNoEvents();
6780
6781 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006782 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6784
6785 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6786 mDispatcher->notifyKey(&keyArgs);
6787 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6788
6789 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6790 ADISPLAY_ID_DEFAULT);
6791 mDispatcher->notifyMotion(&motionArgs);
6792 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6793 window->assertNoEvents();
6794}
6795
6796TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6797 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6798 std::make_shared<FakeApplicationHandle>();
6799 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006800 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6801 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006802 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6803 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006804 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006805 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006806 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6807 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006808 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006809 window->setOwnerInfo(222, 222);
6810 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6811 window->setFocusable(true);
6812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6813 setFocusedWindow(window);
6814 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6815
6816 // With the flag set, window should not get any input
6817 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6818 mDispatcher->notifyKey(&keyArgs);
6819 window->assertNoEvents();
6820
6821 NotifyMotionArgs motionArgs =
6822 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6823 ADISPLAY_ID_DEFAULT);
6824 mDispatcher->notifyMotion(&motionArgs);
6825 window->assertNoEvents();
6826
6827 // When the window is no longer obscured because it went on top, it should get input
6828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6829
6830 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6831 mDispatcher->notifyKey(&keyArgs);
6832 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6833
6834 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6835 ADISPLAY_ID_DEFAULT);
6836 mDispatcher->notifyMotion(&motionArgs);
6837 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6838 window->assertNoEvents();
6839}
6840
Antonio Kantekf16f2832021-09-28 04:39:20 +00006841class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6842protected:
6843 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00006844 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006845 sp<FakeWindowHandle> mWindow;
6846 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00006847 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006848
6849 void SetUp() override {
6850 InputDispatcherTest::SetUp();
6851
6852 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00006853 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006854 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006855 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006856 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006857 mSecondWindow =
6858 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006859 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00006860 mThirdWindow =
6861 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
6862 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
6863 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006864
6865 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00006866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
6867 {SECOND_DISPLAY_ID, {mThirdWindow}}});
6868 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006869 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006870
Antonio Kantek15beb512022-06-13 22:35:41 +00006871 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006872 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00006873 WINDOW_UID, true /* hasPermission */,
6874 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006875 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6876 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006877 mThirdWindow->assertNoEvents();
6878 }
6879
6880 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
6881 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
6882 SECONDARY_WINDOW_UID, true /* hasPermission */,
6883 SECOND_DISPLAY_ID)) {
6884 mWindow->assertNoEvents();
6885 mSecondWindow->assertNoEvents();
6886 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07006887 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006888 }
6889
Antonio Kantek15beb512022-06-13 22:35:41 +00006890 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
6891 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006892 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6893 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006894 mWindow->consumeTouchModeEvent(inTouchMode);
6895 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006896 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00006897 }
6898};
6899
Antonio Kantek26defcf2022-02-08 01:12:27 +00006900TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006901 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00006902 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
6903 windowInfo.ownerPid, windowInfo.ownerUid,
6904 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006905}
6906
Antonio Kantek26defcf2022-02-08 01:12:27 +00006907TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6908 const WindowInfo& windowInfo = *mWindow->getInfo();
6909 int32_t ownerPid = windowInfo.ownerPid;
6910 int32_t ownerUid = windowInfo.ownerUid;
6911 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6912 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006913 ownerUid, false /*hasPermission*/,
6914 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006915 mWindow->assertNoEvents();
6916 mSecondWindow->assertNoEvents();
6917}
6918
6919TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6920 const WindowInfo& windowInfo = *mWindow->getInfo();
6921 int32_t ownerPid = windowInfo.ownerPid;
6922 int32_t ownerUid = windowInfo.ownerUid;
6923 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00006924 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
6925 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006926}
6927
Antonio Kantekf16f2832021-09-28 04:39:20 +00006928TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006929 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006930 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6931 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006932 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006933 mWindow->assertNoEvents();
6934 mSecondWindow->assertNoEvents();
6935}
6936
Antonio Kantek15beb512022-06-13 22:35:41 +00006937TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
6938 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
6939 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6940 windowInfo.ownerPid, windowInfo.ownerUid,
6941 true /*hasPermission*/, SECOND_DISPLAY_ID));
6942 mWindow->assertNoEvents();
6943 mSecondWindow->assertNoEvents();
6944 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
6945}
6946
Antonio Kantek48710e42022-03-24 14:19:30 -07006947TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6948 // Interact with the window first.
6949 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6950 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6951 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6952
6953 // Then remove focus.
6954 mWindow->setFocusable(false);
6955 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6956
6957 // Assert that caller can switch touch mode by owning one of the last interacted window.
6958 const WindowInfo& windowInfo = *mWindow->getInfo();
6959 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6960 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006961 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006962}
6963
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006964class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6965public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006966 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006967 std::shared_ptr<FakeApplicationHandle> application =
6968 std::make_shared<FakeApplicationHandle>();
6969 std::string name = "Fake Spy ";
6970 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006971 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
6972 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006973 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006974 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006975 return spy;
6976 }
6977
6978 sp<FakeWindowHandle> createForeground() {
6979 std::shared_ptr<FakeApplicationHandle> application =
6980 std::make_shared<FakeApplicationHandle>();
6981 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006982 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
6983 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006984 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006985 return window;
6986 }
6987
6988private:
6989 int mSpyCount{0};
6990};
6991
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006992using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006993/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006994 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6995 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006996TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6997 ScopedSilentDeath _silentDeath;
6998
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006999 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08007000 spy->setTrustedOverlay(false);
7001 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
7002 ".* not a trusted overlay");
7003}
7004
7005/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007006 * Input injection into a display with a spy window but no foreground windows should succeed.
7007 */
7008TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007009 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007010 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
7011
7012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7013 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7015 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7016}
7017
7018/**
7019 * Verify the order in which different input windows receive events. The touched foreground window
7020 * (if there is one) should always receive the event first. When there are multiple spy windows, the
7021 * spy windows will receive the event according to their Z-order, where the top-most spy window will
7022 * receive events before ones belows it.
7023 *
7024 * Here, we set up a scenario with four windows in the following Z order from the top:
7025 * spy1, spy2, window, spy3.
7026 * We then inject an event and verify that the foreground "window" receives it first, followed by
7027 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
7028 * window.
7029 */
7030TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
7031 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007032 auto spy1 = createSpy();
7033 auto spy2 = createSpy();
7034 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
7036 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7037 const size_t numChannels = channels.size();
7038
Michael Wright8e9a8562022-02-09 13:44:29 +00007039 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007040 if (!epollFd.ok()) {
7041 FAIL() << "Failed to create epoll fd";
7042 }
7043
7044 for (size_t i = 0; i < numChannels; i++) {
7045 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7046 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7047 FAIL() << "Failed to add fd to epoll";
7048 }
7049 }
7050
7051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7052 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7053 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7054
7055 std::vector<size_t> eventOrder;
7056 std::vector<struct epoll_event> events(numChannels);
7057 for (;;) {
7058 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7059 (100ms).count());
7060 if (nFds < 0) {
7061 FAIL() << "Failed to call epoll_wait";
7062 }
7063 if (nFds == 0) {
7064 break; // epoll_wait timed out
7065 }
7066 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007067 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007068 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007069 channels[i]->consumeMotionDown();
7070 }
7071 }
7072
7073 // Verify the order in which the events were received.
7074 EXPECT_EQ(3u, eventOrder.size());
7075 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7076 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7077 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7078}
7079
7080/**
7081 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7082 */
7083TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7084 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007085 auto spy = createSpy();
7086 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7088
7089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7090 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7091 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7092 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7093 spy->assertNoEvents();
7094}
7095
7096/**
7097 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7098 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7099 * to the window.
7100 */
7101TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7102 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007103 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007104 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7106
7107 // Inject an event outside the spy window's touchable region.
7108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7109 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7111 window->consumeMotionDown();
7112 spy->assertNoEvents();
7113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7114 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7115 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7116 window->consumeMotionUp();
7117 spy->assertNoEvents();
7118
7119 // Inject an event inside the spy window's touchable region.
7120 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7121 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7122 {5, 10}))
7123 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7124 window->consumeMotionDown();
7125 spy->consumeMotionDown();
7126}
7127
7128/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007129 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007130 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007131 */
7132TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7133 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007134 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007135 auto spy = createSpy();
7136 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007137 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007138 spy->setFrame(Rect{0, 0, 20, 20});
7139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7140
7141 // Inject an event outside the spy window's frame and touchable region.
7142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007143 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7144 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7146 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007147 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007148}
7149
7150/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007151 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7152 * pointers that are down within its bounds.
7153 */
7154TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7155 auto windowLeft = createForeground();
7156 windowLeft->setFrame({0, 0, 100, 200});
7157 auto windowRight = createForeground();
7158 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007159 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007160 spy->setFrame({0, 0, 200, 200});
7161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7162
7163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7164 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7165 {50, 50}))
7166 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7167 windowLeft->consumeMotionDown();
7168 spy->consumeMotionDown();
7169
7170 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007171 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007172 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7173 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7174 .pointer(
7175 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7176 .build();
7177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7178 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7179 InputEventInjectionSync::WAIT_FOR_RESULT))
7180 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7181 windowRight->consumeMotionDown();
7182 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7183}
7184
7185/**
7186 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7187 * the spy should receive the second pointer with ACTION_DOWN.
7188 */
7189TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7190 auto window = createForeground();
7191 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007192 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007193 spyRight->setFrame({100, 0, 200, 200});
7194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7195
7196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7197 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7198 {50, 50}))
7199 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7200 window->consumeMotionDown();
7201 spyRight->assertNoEvents();
7202
7203 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007204 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007205 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7206 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7207 .pointer(
7208 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7209 .build();
7210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7211 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7212 InputEventInjectionSync::WAIT_FOR_RESULT))
7213 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7214 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7215 spyRight->consumeMotionDown();
7216}
7217
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007218/**
7219 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7220 * windows should be allowed to control split touch.
7221 */
7222TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007223 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007224 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007225 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007226 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007227
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007228 auto window = createForeground();
7229 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007230
7231 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7232
7233 // First finger down, no window touched.
7234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7235 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7236 {100, 200}))
7237 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7238 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7239 window->assertNoEvents();
7240
7241 // Second finger down on window, the window should receive touch down.
7242 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007243 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007244 .displayId(ADISPLAY_ID_DEFAULT)
7245 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7246 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7247 .x(100)
7248 .y(200))
7249 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7250 .build();
7251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7252 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7253 InputEventInjectionSync::WAIT_FOR_RESULT))
7254 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7255
7256 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7257 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7258}
7259
7260/**
7261 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7262 * do not receive key events.
7263 */
7264TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007265 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007266 spy->setFocusable(false);
7267
7268 auto window = createForeground();
7269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7270 setFocusedWindow(window);
7271 window->consumeFocusEvent(true);
7272
7273 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7274 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7275 window->consumeKeyDown(ADISPLAY_ID_NONE);
7276
7277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7278 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7279 window->consumeKeyUp(ADISPLAY_ID_NONE);
7280
7281 spy->assertNoEvents();
7282}
7283
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007284using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7285
7286/**
7287 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7288 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7289 */
7290TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7291 auto window = createForeground();
7292 auto spy1 = createSpy();
7293 auto spy2 = createSpy();
7294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7295
7296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7297 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7299 window->consumeMotionDown();
7300 spy1->consumeMotionDown();
7301 spy2->consumeMotionDown();
7302
7303 // Pilfer pointers from the second spy window.
7304 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7305 spy2->assertNoEvents();
7306 spy1->consumeMotionCancel();
7307 window->consumeMotionCancel();
7308
7309 // The rest of the gesture should only be sent to the second spy window.
7310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7311 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7312 ADISPLAY_ID_DEFAULT))
7313 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7314 spy2->consumeMotionMove();
7315 spy1->assertNoEvents();
7316 window->assertNoEvents();
7317}
7318
7319/**
7320 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7321 * in the middle of the gesture.
7322 */
7323TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7324 auto window = createForeground();
7325 auto spy = createSpy();
7326 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7327
7328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7329 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7330 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7331 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7332 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7333
7334 window->releaseChannel();
7335
7336 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7337
7338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7339 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7340 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7341 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7342}
7343
7344/**
7345 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7346 * the spy, but not to any other windows.
7347 */
7348TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7349 auto spy = createSpy();
7350 auto window = createForeground();
7351
7352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7353
7354 // First finger down on the window and the spy.
7355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7356 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7357 {100, 200}))
7358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7359 spy->consumeMotionDown();
7360 window->consumeMotionDown();
7361
7362 // Spy window pilfers the pointers.
7363 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7364 window->consumeMotionCancel();
7365
7366 // Second finger down on the window and spy, but the window should not receive the pointer down.
7367 const MotionEvent secondFingerDownEvent =
7368 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7369 .displayId(ADISPLAY_ID_DEFAULT)
7370 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7371 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7372 .x(100)
7373 .y(200))
7374 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7375 .build();
7376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7377 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7378 InputEventInjectionSync::WAIT_FOR_RESULT))
7379 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7380
7381 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7382
7383 // Third finger goes down outside all windows, so injection should fail.
7384 const MotionEvent thirdFingerDownEvent =
7385 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7386 .displayId(ADISPLAY_ID_DEFAULT)
7387 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7388 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7389 .x(100)
7390 .y(200))
7391 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7392 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7393 .build();
7394 ASSERT_EQ(InputEventInjectionResult::FAILED,
7395 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7396 InputEventInjectionSync::WAIT_FOR_RESULT))
7397 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7398
7399 spy->assertNoEvents();
7400 window->assertNoEvents();
7401}
7402
7403/**
7404 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7405 */
7406TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7407 auto spy = createSpy();
7408 spy->setFrame(Rect(0, 0, 100, 100));
7409 auto window = createForeground();
7410 window->setFrame(Rect(0, 0, 200, 200));
7411
7412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7413
7414 // First finger down on the window only
7415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7416 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7417 {150, 150}))
7418 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7419 window->consumeMotionDown();
7420
7421 // Second finger down on the spy and window
7422 const MotionEvent secondFingerDownEvent =
7423 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7424 .displayId(ADISPLAY_ID_DEFAULT)
7425 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7426 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7427 .x(150)
7428 .y(150))
7429 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7430 .build();
7431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7432 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7433 InputEventInjectionSync::WAIT_FOR_RESULT))
7434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7435 spy->consumeMotionDown();
7436 window->consumeMotionPointerDown(1);
7437
7438 // Third finger down on the spy and window
7439 const MotionEvent thirdFingerDownEvent =
7440 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7441 .displayId(ADISPLAY_ID_DEFAULT)
7442 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7443 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7444 .x(150)
7445 .y(150))
7446 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7447 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7448 .build();
7449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7450 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7451 InputEventInjectionSync::WAIT_FOR_RESULT))
7452 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7453 spy->consumeMotionPointerDown(1);
7454 window->consumeMotionPointerDown(2);
7455
7456 // Spy window pilfers the pointers.
7457 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7458 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7459 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7460
7461 spy->assertNoEvents();
7462 window->assertNoEvents();
7463}
7464
7465/**
7466 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7467 * other windows should be canceled. If this results in the cancellation of all pointers for some
7468 * window, then that window should receive ACTION_CANCEL.
7469 */
7470TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7471 auto spy = createSpy();
7472 spy->setFrame(Rect(0, 0, 100, 100));
7473 auto window = createForeground();
7474 window->setFrame(Rect(0, 0, 200, 200));
7475
7476 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7477
7478 // First finger down on both spy and window
7479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7480 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7481 {10, 10}))
7482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7483 window->consumeMotionDown();
7484 spy->consumeMotionDown();
7485
7486 // Second finger down on the spy and window
7487 const MotionEvent secondFingerDownEvent =
7488 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7489 .displayId(ADISPLAY_ID_DEFAULT)
7490 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7491 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7492 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7493 .build();
7494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7495 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7496 InputEventInjectionSync::WAIT_FOR_RESULT))
7497 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7498 spy->consumeMotionPointerDown(1);
7499 window->consumeMotionPointerDown(1);
7500
7501 // Spy window pilfers the pointers.
7502 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7503 window->consumeMotionCancel();
7504
7505 spy->assertNoEvents();
7506 window->assertNoEvents();
7507}
7508
7509/**
7510 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7511 * be sent to other windows
7512 */
7513TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7514 auto spy = createSpy();
7515 spy->setFrame(Rect(0, 0, 100, 100));
7516 auto window = createForeground();
7517 window->setFrame(Rect(0, 0, 200, 200));
7518
7519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7520
7521 // First finger down on both window and spy
7522 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7523 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7524 {10, 10}))
7525 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7526 window->consumeMotionDown();
7527 spy->consumeMotionDown();
7528
7529 // Spy window pilfers the pointers.
7530 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7531 window->consumeMotionCancel();
7532
7533 // Second finger down on the window only
7534 const MotionEvent secondFingerDownEvent =
7535 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7536 .displayId(ADISPLAY_ID_DEFAULT)
7537 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7538 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7539 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7540 .x(150)
7541 .y(150))
7542 .build();
7543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7544 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7545 InputEventInjectionSync::WAIT_FOR_RESULT))
7546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7547 window->consumeMotionDown();
7548 window->assertNoEvents();
7549
7550 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7551 spy->consumeMotionMove();
7552 spy->assertNoEvents();
7553}
7554
Prabir Pradhand65552b2021-10-07 11:23:50 -07007555class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7556public:
7557 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7558 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7559 std::make_shared<FakeApplicationHandle>();
7560 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007561 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7562 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007563 overlay->setFocusable(false);
7564 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007565 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007566 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007567 overlay->setTrustedOverlay(true);
7568
7569 std::shared_ptr<FakeApplicationHandle> application =
7570 std::make_shared<FakeApplicationHandle>();
7571 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007572 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7573 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007574 window->setFocusable(true);
7575 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007576
7577 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7579 setFocusedWindow(window);
7580 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7581 return {std::move(overlay), std::move(window)};
7582 }
7583
7584 void sendFingerEvent(int32_t action) {
7585 NotifyMotionArgs motionArgs =
7586 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7587 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7588 mDispatcher->notifyMotion(&motionArgs);
7589 }
7590
7591 void sendStylusEvent(int32_t action) {
7592 NotifyMotionArgs motionArgs =
7593 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7594 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7595 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7596 mDispatcher->notifyMotion(&motionArgs);
7597 }
7598};
7599
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007600using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7601
7602TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7603 ScopedSilentDeath _silentDeath;
7604
Prabir Pradhand65552b2021-10-07 11:23:50 -07007605 auto [overlay, window] = setupStylusOverlayScenario();
7606 overlay->setTrustedOverlay(false);
7607 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7608 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7609 ".* not a trusted overlay");
7610}
7611
7612TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7613 auto [overlay, window] = setupStylusOverlayScenario();
7614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7615
7616 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7617 overlay->consumeMotionDown();
7618 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7619 overlay->consumeMotionUp();
7620
7621 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7622 window->consumeMotionDown();
7623 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7624 window->consumeMotionUp();
7625
7626 overlay->assertNoEvents();
7627 window->assertNoEvents();
7628}
7629
7630TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7631 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007632 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007633 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7634
7635 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7636 overlay->consumeMotionDown();
7637 window->consumeMotionDown();
7638 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7639 overlay->consumeMotionUp();
7640 window->consumeMotionUp();
7641
7642 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7643 window->consumeMotionDown();
7644 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7645 window->consumeMotionUp();
7646
7647 overlay->assertNoEvents();
7648 window->assertNoEvents();
7649}
7650
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007651/**
7652 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7653 * The scenario is as follows:
7654 * - The stylus interceptor overlay is configured as a spy window.
7655 * - The stylus interceptor spy receives the start of a new stylus gesture.
7656 * - It pilfers pointers and then configures itself to no longer be a spy.
7657 * - The stylus interceptor continues to receive the rest of the gesture.
7658 */
7659TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7660 auto [overlay, window] = setupStylusOverlayScenario();
7661 overlay->setSpy(true);
7662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7663
7664 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7665 overlay->consumeMotionDown();
7666 window->consumeMotionDown();
7667
7668 // The interceptor pilfers the pointers.
7669 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7670 window->consumeMotionCancel();
7671
7672 // The interceptor configures itself so that it is no longer a spy.
7673 overlay->setSpy(false);
7674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7675
7676 // It continues to receive the rest of the stylus gesture.
7677 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7678 overlay->consumeMotionMove();
7679 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7680 overlay->consumeMotionUp();
7681
7682 window->assertNoEvents();
7683}
7684
Prabir Pradhan5735a322022-04-11 17:23:34 +00007685struct User {
7686 int32_t mPid;
7687 int32_t mUid;
7688 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7689 std::unique_ptr<InputDispatcher>& mDispatcher;
7690
7691 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7692 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7693
7694 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7695 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7696 ADISPLAY_ID_DEFAULT, {100, 200},
7697 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7698 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7699 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7700 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7701 }
7702
7703 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7704 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7705 InputEventInjectionSync::WAIT_FOR_RESULT,
7706 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7707 mPolicyFlags);
7708 }
7709
7710 sp<FakeWindowHandle> createWindow() const {
7711 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7712 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007713 sp<FakeWindowHandle> window =
7714 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7715 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007716 window->setOwnerInfo(mPid, mUid);
7717 return window;
7718 }
7719};
7720
7721using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7722
7723TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7724 auto owner = User(mDispatcher, 10, 11);
7725 auto window = owner.createWindow();
7726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7727
7728 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7729 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7730 window->consumeMotionDown();
7731
7732 setFocusedWindow(window);
7733 window->consumeFocusEvent(true);
7734
7735 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7736 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7737 window->consumeKeyDown(ADISPLAY_ID_NONE);
7738}
7739
7740TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7741 auto owner = User(mDispatcher, 10, 11);
7742 auto window = owner.createWindow();
7743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7744
7745 auto rando = User(mDispatcher, 20, 21);
7746 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7747 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7748
7749 setFocusedWindow(window);
7750 window->consumeFocusEvent(true);
7751
7752 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7753 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7754 window->assertNoEvents();
7755}
7756
7757TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7758 auto owner = User(mDispatcher, 10, 11);
7759 auto window = owner.createWindow();
7760 auto spy = owner.createWindow();
7761 spy->setSpy(true);
7762 spy->setTrustedOverlay(true);
7763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7764
7765 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7766 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7767 spy->consumeMotionDown();
7768 window->consumeMotionDown();
7769}
7770
7771TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7772 auto owner = User(mDispatcher, 10, 11);
7773 auto window = owner.createWindow();
7774
7775 auto rando = User(mDispatcher, 20, 21);
7776 auto randosSpy = rando.createWindow();
7777 randosSpy->setSpy(true);
7778 randosSpy->setTrustedOverlay(true);
7779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7780
7781 // The event is targeted at owner's window, so injection should succeed, but the spy should
7782 // not receive the event.
7783 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7784 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7785 randosSpy->assertNoEvents();
7786 window->consumeMotionDown();
7787}
7788
7789TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7790 auto owner = User(mDispatcher, 10, 11);
7791 auto window = owner.createWindow();
7792
7793 auto rando = User(mDispatcher, 20, 21);
7794 auto randosSpy = rando.createWindow();
7795 randosSpy->setSpy(true);
7796 randosSpy->setTrustedOverlay(true);
7797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7798
7799 // A user that has injection permission can inject into any window.
7800 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7801 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7802 ADISPLAY_ID_DEFAULT));
7803 randosSpy->consumeMotionDown();
7804 window->consumeMotionDown();
7805
7806 setFocusedWindow(randosSpy);
7807 randosSpy->consumeFocusEvent(true);
7808
7809 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7810 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7811 window->assertNoEvents();
7812}
7813
7814TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7815 auto owner = User(mDispatcher, 10, 11);
7816 auto window = owner.createWindow();
7817
7818 auto rando = User(mDispatcher, 20, 21);
7819 auto randosWindow = rando.createWindow();
7820 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7821 randosWindow->setWatchOutsideTouch(true);
7822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7823
7824 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7825 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7826 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7827 window->consumeMotionDown();
7828 randosWindow->consumeMotionOutside();
7829}
7830
Garfield Tane84e6f92019-08-29 17:28:41 -07007831} // namespace android::inputdispatcher