blob: aaf50ce5ed43633ffb03b474e0f92f587347699e [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
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002403/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002404 * Ensure the correct coordinate spaces are used by InputDispatcher.
2405 *
2406 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2407 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2408 * space.
2409 */
2410class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2411public:
2412 void SetUp() override {
2413 InputDispatcherTest::SetUp();
2414 mDisplayInfos.clear();
2415 mWindowInfos.clear();
2416 }
2417
2418 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2419 gui::DisplayInfo info;
2420 info.displayId = displayId;
2421 info.transform = transform;
2422 mDisplayInfos.push_back(std::move(info));
2423 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2424 }
2425
2426 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2427 mWindowInfos.push_back(*windowHandle->getInfo());
2428 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2429 }
2430
2431 // Set up a test scenario where the display has a scaled projection and there are two windows
2432 // on the display.
2433 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2434 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2435 // respectively.
2436 ui::Transform displayTransform;
2437 displayTransform.set(2, 0, 0, 4);
2438 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2439
2440 std::shared_ptr<FakeApplicationHandle> application =
2441 std::make_shared<FakeApplicationHandle>();
2442
2443 // Add two windows to the display. Their frames are represented in the display space.
2444 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002445 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2446 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002447 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2448 addWindow(firstWindow);
2449
2450 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002451 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2452 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002453 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2454 addWindow(secondWindow);
2455 return {std::move(firstWindow), std::move(secondWindow)};
2456 }
2457
2458private:
2459 std::vector<gui::DisplayInfo> mDisplayInfos;
2460 std::vector<gui::WindowInfo> mWindowInfos;
2461};
2462
2463TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2464 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2465 // Send down to the first window. The point is represented in the display space. The point is
2466 // selected so that if the hit test was done with the transform applied to it, then it would
2467 // end up in the incorrect window.
2468 NotifyMotionArgs downMotionArgs =
2469 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2470 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2471 mDispatcher->notifyMotion(&downMotionArgs);
2472
2473 firstWindow->consumeMotionDown();
2474 secondWindow->assertNoEvents();
2475}
2476
2477// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2478// the event should be treated as being in the logical display space.
2479TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2480 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2481 // Send down to the first window. The point is represented in the logical display space. The
2482 // point is selected so that if the hit test was done in logical display space, then it would
2483 // end up in the incorrect window.
2484 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2485 PointF{75 * 2, 55 * 4});
2486
2487 firstWindow->consumeMotionDown();
2488 secondWindow->assertNoEvents();
2489}
2490
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002491// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2492// event should be treated as being in the logical display space.
2493TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2494 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2495
2496 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2497 ui::Transform injectedEventTransform;
2498 injectedEventTransform.set(matrix);
2499 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2500 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2501
2502 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2503 .displayId(ADISPLAY_ID_DEFAULT)
2504 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2505 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2506 .x(untransformedPoint.x)
2507 .y(untransformedPoint.y))
2508 .build();
2509 event.transform(matrix);
2510
2511 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2512 InputEventInjectionSync::WAIT_FOR_RESULT);
2513
2514 firstWindow->consumeMotionDown();
2515 secondWindow->assertNoEvents();
2516}
2517
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002518TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2519 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2520
2521 // Send down to the second window.
2522 NotifyMotionArgs downMotionArgs =
2523 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2524 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2525 mDispatcher->notifyMotion(&downMotionArgs);
2526
2527 firstWindow->assertNoEvents();
2528 const MotionEvent* event = secondWindow->consumeMotion();
2529 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2530
2531 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2532 EXPECT_EQ(300, event->getRawX(0));
2533 EXPECT_EQ(880, event->getRawY(0));
2534
2535 // Ensure that the x and y values are in the window's coordinate space.
2536 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2537 // the logical display space. This will be the origin of the window space.
2538 EXPECT_EQ(100, event->getX(0));
2539 EXPECT_EQ(80, event->getY(0));
2540}
2541
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002542using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2543 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002544
2545class TransferTouchFixture : public InputDispatcherTest,
2546 public ::testing::WithParamInterface<TransferFunction> {};
2547
2548TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002549 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002550
2551 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002552 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002553 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2554 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002555 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002556 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2557 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002558
2559 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002561
2562 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002563 NotifyMotionArgs downMotionArgs =
2564 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2565 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002566 mDispatcher->notifyMotion(&downMotionArgs);
2567 // Only the first window should get the down event
2568 firstWindow->consumeMotionDown();
2569 secondWindow->assertNoEvents();
2570
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002571 // Transfer touch to the second window
2572 TransferFunction f = GetParam();
2573 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2574 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002575 // The first window gets cancel and the second gets down
2576 firstWindow->consumeMotionCancel();
2577 secondWindow->consumeMotionDown();
2578
2579 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002580 NotifyMotionArgs upMotionArgs =
2581 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2582 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002583 mDispatcher->notifyMotion(&upMotionArgs);
2584 // The first window gets no events and the second gets up
2585 firstWindow->assertNoEvents();
2586 secondWindow->consumeMotionUp();
2587}
2588
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002589/**
2590 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2591 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2592 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2593 * natural to the user.
2594 * In this test, we are sending a pointer to both spy window and first window. We then try to
2595 * transfer touch to the second window. The dispatcher should identify the first window as the
2596 * one that should lose the gesture, and therefore the action should be to move the gesture from
2597 * the first window to the second.
2598 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2599 * the other API, as well.
2600 */
2601TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2603
2604 // Create a couple of windows + a spy window
2605 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002606 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002607 spyWindow->setTrustedOverlay(true);
2608 spyWindow->setSpy(true);
2609 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002610 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002611 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002612 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002613
2614 // Add the windows to the dispatcher
2615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2616
2617 // Send down to the first window
2618 NotifyMotionArgs downMotionArgs =
2619 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2620 ADISPLAY_ID_DEFAULT);
2621 mDispatcher->notifyMotion(&downMotionArgs);
2622 // Only the first window and spy should get the down event
2623 spyWindow->consumeMotionDown();
2624 firstWindow->consumeMotionDown();
2625
2626 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2627 // if f === 'transferTouch'.
2628 TransferFunction f = GetParam();
2629 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2630 ASSERT_TRUE(success);
2631 // The first window gets cancel and the second gets down
2632 firstWindow->consumeMotionCancel();
2633 secondWindow->consumeMotionDown();
2634
2635 // Send up event to the second window
2636 NotifyMotionArgs upMotionArgs =
2637 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2638 ADISPLAY_ID_DEFAULT);
2639 mDispatcher->notifyMotion(&upMotionArgs);
2640 // The first window gets no events and the second+spy get up
2641 firstWindow->assertNoEvents();
2642 spyWindow->consumeMotionUp();
2643 secondWindow->consumeMotionUp();
2644}
2645
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002646TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002647 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002648
2649 PointF touchPoint = {10, 10};
2650
2651 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002652 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002653 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2654 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002655 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002656 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002657 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2658 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002659 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002660
2661 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002663
2664 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002665 NotifyMotionArgs downMotionArgs =
2666 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2667 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002668 mDispatcher->notifyMotion(&downMotionArgs);
2669 // Only the first window should get the down event
2670 firstWindow->consumeMotionDown();
2671 secondWindow->assertNoEvents();
2672
2673 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002674 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002675 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002676 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002677 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2678 // Only the first window should get the pointer down event
2679 firstWindow->consumeMotionPointerDown(1);
2680 secondWindow->assertNoEvents();
2681
2682 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002683 TransferFunction f = GetParam();
2684 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2685 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002686 // The first window gets cancel and the second gets down and pointer down
2687 firstWindow->consumeMotionCancel();
2688 secondWindow->consumeMotionDown();
2689 secondWindow->consumeMotionPointerDown(1);
2690
2691 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002692 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002693 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002694 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002695 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2696 // The first window gets nothing and the second gets pointer up
2697 firstWindow->assertNoEvents();
2698 secondWindow->consumeMotionPointerUp(1);
2699
2700 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002701 NotifyMotionArgs upMotionArgs =
2702 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2703 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002704 mDispatcher->notifyMotion(&upMotionArgs);
2705 // The first window gets nothing and the second gets up
2706 firstWindow->assertNoEvents();
2707 secondWindow->consumeMotionUp();
2708}
2709
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002710// For the cases of single pointer touch and two pointers non-split touch, the api's
2711// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2712// for the case where there are multiple pointers split across several windows.
2713INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2714 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002715 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2716 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002717 return dispatcher->transferTouch(destChannelToken,
2718 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002719 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002720 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2721 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002722 return dispatcher->transferTouchFocus(from, to,
2723 false /*isDragAndDrop*/);
2724 }));
2725
Svet Ganov5d3bc372020-01-26 23:11:07 -08002726TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002727 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002728
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002729 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002730 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2731 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002732 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002733
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002734 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002735 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2736 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002737 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002738
2739 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002741
2742 PointF pointInFirst = {300, 200};
2743 PointF pointInSecond = {300, 600};
2744
2745 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002746 NotifyMotionArgs firstDownMotionArgs =
2747 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2748 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002749 mDispatcher->notifyMotion(&firstDownMotionArgs);
2750 // Only the first window should get the down event
2751 firstWindow->consumeMotionDown();
2752 secondWindow->assertNoEvents();
2753
2754 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002755 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002756 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002757 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002758 mDispatcher->notifyMotion(&secondDownMotionArgs);
2759 // The first window gets a move and the second a down
2760 firstWindow->consumeMotionMove();
2761 secondWindow->consumeMotionDown();
2762
2763 // Transfer touch focus to the second window
2764 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2765 // The first window gets cancel and the new gets pointer down (it already saw down)
2766 firstWindow->consumeMotionCancel();
2767 secondWindow->consumeMotionPointerDown(1);
2768
2769 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002770 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002771 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002772 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002773 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2774 // The first window gets nothing and the second gets pointer up
2775 firstWindow->assertNoEvents();
2776 secondWindow->consumeMotionPointerUp(1);
2777
2778 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002779 NotifyMotionArgs upMotionArgs =
2780 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2781 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002782 mDispatcher->notifyMotion(&upMotionArgs);
2783 // The first window gets nothing and the second gets up
2784 firstWindow->assertNoEvents();
2785 secondWindow->consumeMotionUp();
2786}
2787
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002788// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2789// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2790// touch is not supported, so the touch should continue on those windows and the transferred-to
2791// window should get nothing.
2792TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2793 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2794
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002795 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002796 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2797 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002798 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002799
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002800 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002801 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2802 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002803 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002804
2805 // Add the windows to the dispatcher
2806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2807
2808 PointF pointInFirst = {300, 200};
2809 PointF pointInSecond = {300, 600};
2810
2811 // Send down to the first window
2812 NotifyMotionArgs firstDownMotionArgs =
2813 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2814 ADISPLAY_ID_DEFAULT, {pointInFirst});
2815 mDispatcher->notifyMotion(&firstDownMotionArgs);
2816 // Only the first window should get the down event
2817 firstWindow->consumeMotionDown();
2818 secondWindow->assertNoEvents();
2819
2820 // Send down to the second window
2821 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002822 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002823 {pointInFirst, pointInSecond});
2824 mDispatcher->notifyMotion(&secondDownMotionArgs);
2825 // The first window gets a move and the second a down
2826 firstWindow->consumeMotionMove();
2827 secondWindow->consumeMotionDown();
2828
2829 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002830 const bool transferred =
2831 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002832 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2833 ASSERT_FALSE(transferred);
2834 firstWindow->assertNoEvents();
2835 secondWindow->assertNoEvents();
2836
2837 // The rest of the dispatch should proceed as normal
2838 // Send pointer up to the second window
2839 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002840 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002841 {pointInFirst, pointInSecond});
2842 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2843 // The first window gets MOVE and the second gets pointer up
2844 firstWindow->consumeMotionMove();
2845 secondWindow->consumeMotionUp();
2846
2847 // Send up event to the first window
2848 NotifyMotionArgs upMotionArgs =
2849 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2850 ADISPLAY_ID_DEFAULT);
2851 mDispatcher->notifyMotion(&upMotionArgs);
2852 // The first window gets nothing and the second gets up
2853 firstWindow->consumeMotionUp();
2854 secondWindow->assertNoEvents();
2855}
2856
Arthur Hungabbb9d82021-09-01 14:52:30 +00002857// This case will create two windows and one mirrored window on the default display and mirror
2858// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2859// the windows info of second display before default display.
2860TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2861 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2862 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002863 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002864 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002865 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002866 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002867 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002868
2869 sp<FakeWindowHandle> mirrorWindowInPrimary =
2870 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2871 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002872
2873 sp<FakeWindowHandle> firstWindowInSecondary =
2874 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2875 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002876
2877 sp<FakeWindowHandle> secondWindowInSecondary =
2878 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2879 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002880
2881 // Update window info, let it find window handle of second display first.
2882 mDispatcher->setInputWindows(
2883 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2884 {ADISPLAY_ID_DEFAULT,
2885 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2886
2887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2888 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2889 {50, 50}))
2890 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2891
2892 // Window should receive motion event.
2893 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2894
2895 // Transfer touch focus
2896 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2897 secondWindowInPrimary->getToken()));
2898 // The first window gets cancel.
2899 firstWindowInPrimary->consumeMotionCancel();
2900 secondWindowInPrimary->consumeMotionDown();
2901
2902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2903 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2904 ADISPLAY_ID_DEFAULT, {150, 50}))
2905 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2906 firstWindowInPrimary->assertNoEvents();
2907 secondWindowInPrimary->consumeMotionMove();
2908
2909 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2910 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2911 {150, 50}))
2912 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2913 firstWindowInPrimary->assertNoEvents();
2914 secondWindowInPrimary->consumeMotionUp();
2915}
2916
2917// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2918// 'transferTouch' api.
2919TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2920 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2921 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002922 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002923 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002924 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002925 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002926 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002927
2928 sp<FakeWindowHandle> mirrorWindowInPrimary =
2929 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2930 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002931
2932 sp<FakeWindowHandle> firstWindowInSecondary =
2933 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2934 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002935
2936 sp<FakeWindowHandle> secondWindowInSecondary =
2937 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2938 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002939
2940 // Update window info, let it find window handle of second display first.
2941 mDispatcher->setInputWindows(
2942 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2943 {ADISPLAY_ID_DEFAULT,
2944 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2945
2946 // Touch on second display.
2947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2948 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2950
2951 // Window should receive motion event.
2952 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2953
2954 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002955 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002956
2957 // The first window gets cancel.
2958 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2959 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2960
2961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2962 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2963 SECOND_DISPLAY_ID, {150, 50}))
2964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2965 firstWindowInPrimary->assertNoEvents();
2966 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2967
2968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2969 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2970 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2971 firstWindowInPrimary->assertNoEvents();
2972 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2973}
2974
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002975TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002976 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002977 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2978 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002979
Vishnu Nair47074b82020-08-14 11:54:47 -07002980 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002982 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002983
2984 window->consumeFocusEvent(true);
2985
2986 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2987 mDispatcher->notifyKey(&keyArgs);
2988
2989 // Window should receive key down event.
2990 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2991}
2992
2993TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002994 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002995 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2996 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002997
Arthur Hung72d8dc32020-03-28 00:48:39 +00002998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002999
3000 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3001 mDispatcher->notifyKey(&keyArgs);
3002 mDispatcher->waitForIdle();
3003
3004 window->assertNoEvents();
3005}
3006
3007// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3008TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003009 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003010 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3011 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012
Arthur Hung72d8dc32020-03-28 00:48:39 +00003013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003014
3015 // Send key
3016 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3017 mDispatcher->notifyKey(&keyArgs);
3018 // Send motion
3019 NotifyMotionArgs motionArgs =
3020 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3021 ADISPLAY_ID_DEFAULT);
3022 mDispatcher->notifyMotion(&motionArgs);
3023
3024 // Window should receive only the motion event
3025 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3026 window->assertNoEvents(); // Key event or focus event will not be received
3027}
3028
arthurhungea3f4fc2020-12-21 23:18:53 +08003029TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3030 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3031
arthurhungea3f4fc2020-12-21 23:18:53 +08003032 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003033 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3034 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003035 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003036
arthurhungea3f4fc2020-12-21 23:18:53 +08003037 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003038 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3039 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003040 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003041
3042 // Add the windows to the dispatcher
3043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3044
3045 PointF pointInFirst = {300, 200};
3046 PointF pointInSecond = {300, 600};
3047
3048 // Send down to the first window
3049 NotifyMotionArgs firstDownMotionArgs =
3050 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3051 ADISPLAY_ID_DEFAULT, {pointInFirst});
3052 mDispatcher->notifyMotion(&firstDownMotionArgs);
3053 // Only the first window should get the down event
3054 firstWindow->consumeMotionDown();
3055 secondWindow->assertNoEvents();
3056
3057 // Send down to the second window
3058 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003059 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003060 {pointInFirst, pointInSecond});
3061 mDispatcher->notifyMotion(&secondDownMotionArgs);
3062 // The first window gets a move and the second a down
3063 firstWindow->consumeMotionMove();
3064 secondWindow->consumeMotionDown();
3065
3066 // Send pointer cancel to the second window
3067 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003068 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003069 {pointInFirst, pointInSecond});
3070 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3071 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3072 // The first window gets move and the second gets cancel.
3073 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3074 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3075
3076 // Send up event.
3077 NotifyMotionArgs upMotionArgs =
3078 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3079 ADISPLAY_ID_DEFAULT);
3080 mDispatcher->notifyMotion(&upMotionArgs);
3081 // The first window gets up and the second gets nothing.
3082 firstWindow->consumeMotionUp();
3083 secondWindow->assertNoEvents();
3084}
3085
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003086TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3087 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3088
3089 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003090 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3092 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3093 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3094 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3095
3096 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3097 window->assertNoEvents();
3098 mDispatcher->waitForIdle();
3099}
3100
chaviwd1c23182019-12-20 18:44:56 -08003101class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003102public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003103 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003104 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003105 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003106 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003107 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003108 }
3109
chaviwd1c23182019-12-20 18:44:56 -08003110 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3111
3112 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3113 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3114 expectedDisplayId, expectedFlags);
3115 }
3116
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003117 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3118
3119 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3120
chaviwd1c23182019-12-20 18:44:56 -08003121 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3122 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3123 expectedDisplayId, expectedFlags);
3124 }
3125
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003126 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3127 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3128 expectedDisplayId, expectedFlags);
3129 }
3130
chaviwd1c23182019-12-20 18:44:56 -08003131 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3132 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3133 expectedDisplayId, expectedFlags);
3134 }
3135
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003136 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3137 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3138 expectedDisplayId, expectedFlags);
3139 }
3140
Arthur Hungfbfa5722021-11-16 02:45:54 +00003141 void consumeMotionPointerDown(int32_t pointerIdx) {
3142 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3143 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3144 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3145 0 /*expectedFlags*/);
3146 }
3147
Evan Rosky84f07f02021-04-16 10:42:42 -07003148 MotionEvent* consumeMotion() {
3149 InputEvent* event = mInputReceiver->consume();
3150 if (!event) {
3151 ADD_FAILURE() << "No event was produced";
3152 return nullptr;
3153 }
3154 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3155 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3156 return nullptr;
3157 }
3158 return static_cast<MotionEvent*>(event);
3159 }
3160
chaviwd1c23182019-12-20 18:44:56 -08003161 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3162
3163private:
3164 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003165};
3166
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003167using InputDispatcherMonitorTest = InputDispatcherTest;
3168
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003169/**
3170 * Two entities that receive touch: A window, and a global monitor.
3171 * The touch goes to the window, and then the window disappears.
3172 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3173 * for the monitor, as well.
3174 * 1. foregroundWindow
3175 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3176 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003177TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003178 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3179 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003180 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003181
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003182 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003183
3184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3186 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3187 {100, 200}))
3188 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3189
3190 // Both the foreground window and the global monitor should receive the touch down
3191 window->consumeMotionDown();
3192 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3193
3194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3195 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3196 ADISPLAY_ID_DEFAULT, {110, 200}))
3197 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3198
3199 window->consumeMotionMove();
3200 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3201
3202 // Now the foreground window goes away
3203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3204 window->consumeMotionCancel();
3205 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3206
3207 // If more events come in, there will be no more foreground window to send them to. This will
3208 // cause a cancel for the monitor, as well.
3209 ASSERT_EQ(InputEventInjectionResult::FAILED,
3210 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3211 ADISPLAY_ID_DEFAULT, {120, 200}))
3212 << "Injection should fail because the window was removed";
3213 window->assertNoEvents();
3214 // Global monitor now gets the cancel
3215 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3216}
3217
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003218TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003219 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003220 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3221 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003223
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003224 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003225
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003227 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003228 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003229 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003230 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003231}
3232
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003233TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3234 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003235
Chris Yea209fde2020-07-22 13:54:51 -07003236 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003237 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3238 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003240
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003241 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003242 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003243 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003244 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003245 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003246
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003247 // Pilfer pointers from the monitor.
3248 // This should not do anything and the window should continue to receive events.
3249 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003250
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003252 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3253 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003254 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003255
3256 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3257 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003258}
3259
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003260TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003261 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003262 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3263 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3265 window->setWindowOffset(20, 40);
3266 window->setWindowTransform(0, 1, -1, 0);
3267
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003268 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003269
3270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3271 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3273 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3274 MotionEvent* event = monitor.consumeMotion();
3275 // Even though window has transform, gesture monitor must not.
3276 ASSERT_EQ(ui::Transform(), event->getTransform());
3277}
3278
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003279TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003280 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003281 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003282
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003283 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003284 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003285 << "Injection should fail if there is a monitor, but no touchable window";
3286 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003287}
3288
chaviw81e2bb92019-12-18 15:03:51 -08003289TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003290 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003291 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3292 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003293
Arthur Hung72d8dc32020-03-28 00:48:39 +00003294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003295
3296 NotifyMotionArgs motionArgs =
3297 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3298 ADISPLAY_ID_DEFAULT);
3299
3300 mDispatcher->notifyMotion(&motionArgs);
3301 // Window should receive motion down event.
3302 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3303
3304 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003305 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003306 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3307 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3308 motionArgs.pointerCoords[0].getX() - 10);
3309
3310 mDispatcher->notifyMotion(&motionArgs);
3311 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3312 0 /*expectedFlags*/);
3313}
3314
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003315/**
3316 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3317 * the device default right away. In the test scenario, we check both the default value,
3318 * and the action of enabling / disabling.
3319 */
3320TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003321 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003322 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3323 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003324 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003325
3326 // Set focused application.
3327 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003328 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003329
3330 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003332 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003333 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3334
3335 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003336 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003338 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3339
3340 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003341 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003342 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003343 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003344 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003346 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003347 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3348
3349 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003350 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003352 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3353
3354 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003355 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003356 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003357 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003358 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003360 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003361 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3362
3363 window->assertNoEvents();
3364}
3365
Gang Wange9087892020-01-07 12:17:14 -05003366TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003367 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003368 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3369 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003370
3371 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003372 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003373
Arthur Hung72d8dc32020-03-28 00:48:39 +00003374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003375 setFocusedWindow(window);
3376
Gang Wange9087892020-01-07 12:17:14 -05003377 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3378
3379 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3380 mDispatcher->notifyKey(&keyArgs);
3381
3382 InputEvent* event = window->consume();
3383 ASSERT_NE(event, nullptr);
3384
3385 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3386 ASSERT_NE(verified, nullptr);
3387 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3388
3389 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3390 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3391 ASSERT_EQ(keyArgs.source, verified->source);
3392 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3393
3394 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3395
3396 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003397 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003398 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003399 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3400 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3401 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3402 ASSERT_EQ(0, verifiedKey.repeatCount);
3403}
3404
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003405TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003407 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3408 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003409
3410 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3411
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003412 ui::Transform transform;
3413 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3414
3415 gui::DisplayInfo displayInfo;
3416 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3417 displayInfo.transform = transform;
3418
3419 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003420
3421 NotifyMotionArgs motionArgs =
3422 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3423 ADISPLAY_ID_DEFAULT);
3424 mDispatcher->notifyMotion(&motionArgs);
3425
3426 InputEvent* event = window->consume();
3427 ASSERT_NE(event, nullptr);
3428
3429 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3430 ASSERT_NE(verified, nullptr);
3431 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3432
3433 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3434 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3435 EXPECT_EQ(motionArgs.source, verified->source);
3436 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3437
3438 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3439
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003440 const vec2 rawXY =
3441 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3442 motionArgs.pointerCoords[0].getXYValue());
3443 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3444 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003445 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003446 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003447 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003448 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3449 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3450}
3451
chaviw09c8d2d2020-08-24 15:48:26 -07003452/**
3453 * Ensure that separate calls to sign the same data are generating the same key.
3454 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3455 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3456 * tests.
3457 */
3458TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3459 KeyEvent event = getTestKeyEvent();
3460 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3461
3462 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3463 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3464 ASSERT_EQ(hmac1, hmac2);
3465}
3466
3467/**
3468 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3469 */
3470TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3471 KeyEvent event = getTestKeyEvent();
3472 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3473 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3474
3475 verifiedEvent.deviceId += 1;
3476 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3477
3478 verifiedEvent.source += 1;
3479 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3480
3481 verifiedEvent.eventTimeNanos += 1;
3482 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3483
3484 verifiedEvent.displayId += 1;
3485 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3486
3487 verifiedEvent.action += 1;
3488 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3489
3490 verifiedEvent.downTimeNanos += 1;
3491 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3492
3493 verifiedEvent.flags += 1;
3494 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3495
3496 verifiedEvent.keyCode += 1;
3497 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3498
3499 verifiedEvent.scanCode += 1;
3500 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3501
3502 verifiedEvent.metaState += 1;
3503 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3504
3505 verifiedEvent.repeatCount += 1;
3506 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3507}
3508
Vishnu Nair958da932020-08-21 17:12:37 -07003509TEST_F(InputDispatcherTest, SetFocusedWindow) {
3510 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3511 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003512 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003513 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003514 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003515 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3516
3517 // Top window is also focusable but is not granted focus.
3518 windowTop->setFocusable(true);
3519 windowSecond->setFocusable(true);
3520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3521 setFocusedWindow(windowSecond);
3522
3523 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3525 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003526
3527 // Focused window should receive event.
3528 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3529 windowTop->assertNoEvents();
3530}
3531
3532TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3533 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3534 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003535 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003536 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3537
3538 window->setFocusable(true);
3539 // Release channel for window is no longer valid.
3540 window->releaseChannel();
3541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3542 setFocusedWindow(window);
3543
3544 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003545 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3546 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003547
3548 // window channel is invalid, so it should not receive any input event.
3549 window->assertNoEvents();
3550}
3551
3552TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3553 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3554 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003555 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003556 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003557 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3558
Vishnu Nair958da932020-08-21 17:12:37 -07003559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3560 setFocusedWindow(window);
3561
3562 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003563 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3564 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003565
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003566 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003567 window->assertNoEvents();
3568}
3569
3570TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3572 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003573 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003574 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003575 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003576 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3577
3578 windowTop->setFocusable(true);
3579 windowSecond->setFocusable(true);
3580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3581 setFocusedWindow(windowTop);
3582 windowTop->consumeFocusEvent(true);
3583
3584 setFocusedWindow(windowSecond, windowTop);
3585 windowSecond->consumeFocusEvent(true);
3586 windowTop->consumeFocusEvent(false);
3587
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3589 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003590
3591 // Focused window should receive event.
3592 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3593}
3594
3595TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3596 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3597 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003598 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003599 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003600 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003601 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3602
3603 windowTop->setFocusable(true);
3604 windowSecond->setFocusable(true);
3605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3606 setFocusedWindow(windowSecond, windowTop);
3607
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003608 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3609 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003610
3611 // Event should be dropped.
3612 windowTop->assertNoEvents();
3613 windowSecond->assertNoEvents();
3614}
3615
3616TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3617 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3618 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003619 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003620 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003621 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3622 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003623 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3624
3625 window->setFocusable(true);
3626 previousFocusedWindow->setFocusable(true);
3627 window->setVisible(false);
3628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3629 setFocusedWindow(previousFocusedWindow);
3630 previousFocusedWindow->consumeFocusEvent(true);
3631
3632 // Requesting focus on invisible window takes focus from currently focused window.
3633 setFocusedWindow(window);
3634 previousFocusedWindow->consumeFocusEvent(false);
3635
3636 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003638 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003639 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003640
3641 // Window does not get focus event or key down.
3642 window->assertNoEvents();
3643
3644 // Window becomes visible.
3645 window->setVisible(true);
3646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3647
3648 // Window receives focus event.
3649 window->consumeFocusEvent(true);
3650 // Focused window receives key down.
3651 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3652}
3653
Vishnu Nair599f1412021-06-21 10:39:58 -07003654TEST_F(InputDispatcherTest, DisplayRemoved) {
3655 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3656 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003657 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003658 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3659
3660 // window is granted focus.
3661 window->setFocusable(true);
3662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3663 setFocusedWindow(window);
3664 window->consumeFocusEvent(true);
3665
3666 // When a display is removed window loses focus.
3667 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3668 window->consumeFocusEvent(false);
3669}
3670
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003671/**
3672 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3673 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3674 * of the 'slipperyEnterWindow'.
3675 *
3676 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3677 * a way so that the touched location is no longer covered by the top window.
3678 *
3679 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3680 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3681 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3682 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3683 * with ACTION_DOWN).
3684 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3685 * window moved itself away from the touched location and had Flag::SLIPPERY.
3686 *
3687 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3688 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3689 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3690 *
3691 * In this test, we ensure that the event received by the bottom window has
3692 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3693 */
3694TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003695 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3696 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003697
3698 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3699 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3700
3701 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003702 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003703 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003704 // Make sure this one overlaps the bottom window
3705 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3706 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3707 // one. Windows with the same owner are not considered to be occluding each other.
3708 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3709
3710 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003711 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003712 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3713
3714 mDispatcher->setInputWindows(
3715 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3716
3717 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3718 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3719 ADISPLAY_ID_DEFAULT, {{50, 50}});
3720 mDispatcher->notifyMotion(&args);
3721 slipperyExitWindow->consumeMotionDown();
3722 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3723 mDispatcher->setInputWindows(
3724 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3725
3726 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3727 ADISPLAY_ID_DEFAULT, {{51, 51}});
3728 mDispatcher->notifyMotion(&args);
3729
3730 slipperyExitWindow->consumeMotionCancel();
3731
3732 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3733 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3734}
3735
Garfield Tan1c7bc862020-01-28 13:24:04 -08003736class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3737protected:
3738 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3739 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3740
Chris Yea209fde2020-07-22 13:54:51 -07003741 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003742 sp<FakeWindowHandle> mWindow;
3743
3744 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003745 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003746 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003747 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003748 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3749 ASSERT_EQ(OK, mDispatcher->start());
3750
3751 setUpWindow();
3752 }
3753
3754 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003755 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003756 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003757
Vishnu Nair47074b82020-08-14 11:54:47 -07003758 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003760 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003761 mWindow->consumeFocusEvent(true);
3762 }
3763
Chris Ye2ad95392020-09-01 13:44:44 -07003764 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003765 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003766 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003767 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3768 mDispatcher->notifyKey(&keyArgs);
3769
3770 // Window should receive key down event.
3771 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3772 }
3773
3774 void expectKeyRepeatOnce(int32_t repeatCount) {
3775 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3776 InputEvent* repeatEvent = mWindow->consume();
3777 ASSERT_NE(nullptr, repeatEvent);
3778
3779 uint32_t eventType = repeatEvent->getType();
3780 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3781
3782 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3783 uint32_t eventAction = repeatKeyEvent->getAction();
3784 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3785 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3786 }
3787
Chris Ye2ad95392020-09-01 13:44:44 -07003788 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003789 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003790 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003791 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3792 mDispatcher->notifyKey(&keyArgs);
3793
3794 // Window should receive key down event.
3795 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3796 0 /*expectedFlags*/);
3797 }
3798};
3799
3800TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003801 sendAndConsumeKeyDown(1 /* deviceId */);
3802 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3803 expectKeyRepeatOnce(repeatCount);
3804 }
3805}
3806
3807TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3808 sendAndConsumeKeyDown(1 /* deviceId */);
3809 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3810 expectKeyRepeatOnce(repeatCount);
3811 }
3812 sendAndConsumeKeyDown(2 /* deviceId */);
3813 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003814 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3815 expectKeyRepeatOnce(repeatCount);
3816 }
3817}
3818
3819TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003820 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003821 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003822 sendAndConsumeKeyUp(1 /* deviceId */);
3823 mWindow->assertNoEvents();
3824}
3825
3826TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3827 sendAndConsumeKeyDown(1 /* deviceId */);
3828 expectKeyRepeatOnce(1 /*repeatCount*/);
3829 sendAndConsumeKeyDown(2 /* deviceId */);
3830 expectKeyRepeatOnce(1 /*repeatCount*/);
3831 // Stale key up from device 1.
3832 sendAndConsumeKeyUp(1 /* deviceId */);
3833 // Device 2 is still down, keep repeating
3834 expectKeyRepeatOnce(2 /*repeatCount*/);
3835 expectKeyRepeatOnce(3 /*repeatCount*/);
3836 // Device 2 key up
3837 sendAndConsumeKeyUp(2 /* deviceId */);
3838 mWindow->assertNoEvents();
3839}
3840
3841TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3842 sendAndConsumeKeyDown(1 /* deviceId */);
3843 expectKeyRepeatOnce(1 /*repeatCount*/);
3844 sendAndConsumeKeyDown(2 /* deviceId */);
3845 expectKeyRepeatOnce(1 /*repeatCount*/);
3846 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3847 sendAndConsumeKeyUp(2 /* deviceId */);
3848 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003849 mWindow->assertNoEvents();
3850}
3851
liushenxiang42232912021-05-21 20:24:09 +08003852TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3853 sendAndConsumeKeyDown(DEVICE_ID);
3854 expectKeyRepeatOnce(1 /*repeatCount*/);
3855 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3856 mDispatcher->notifyDeviceReset(&args);
3857 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3858 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3859 mWindow->assertNoEvents();
3860}
3861
Garfield Tan1c7bc862020-01-28 13:24:04 -08003862TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003863 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003864 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3865 InputEvent* repeatEvent = mWindow->consume();
3866 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3867 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3868 IdGenerator::getSource(repeatEvent->getId()));
3869 }
3870}
3871
3872TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003873 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003874
3875 std::unordered_set<int32_t> idSet;
3876 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3877 InputEvent* repeatEvent = mWindow->consume();
3878 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3879 int32_t id = repeatEvent->getId();
3880 EXPECT_EQ(idSet.end(), idSet.find(id));
3881 idSet.insert(id);
3882 }
3883}
3884
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003885/* Test InputDispatcher for MultiDisplay */
3886class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3887public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003888 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003889 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003890
Chris Yea209fde2020-07-22 13:54:51 -07003891 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003892 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003893 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003894
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003895 // Set focus window for primary display, but focused display would be second one.
3896 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003897 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003899 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003900 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003901
Chris Yea209fde2020-07-22 13:54:51 -07003902 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003903 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003904 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003905 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003906 // Set focus display to second one.
3907 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3908 // Set focus window for second display.
3909 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003910 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003911 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003912 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003913 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003914 }
3915
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003916 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003917 InputDispatcherTest::TearDown();
3918
Chris Yea209fde2020-07-22 13:54:51 -07003919 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003920 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003921 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003922 windowInSecondary.clear();
3923 }
3924
3925protected:
Chris Yea209fde2020-07-22 13:54:51 -07003926 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003927 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003928 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003929 sp<FakeWindowHandle> windowInSecondary;
3930};
3931
3932TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3933 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3935 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3936 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003937 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003938 windowInSecondary->assertNoEvents();
3939
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003940 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3942 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003944 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003945 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003946}
3947
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003948TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003949 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3951 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003952 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003953 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003954 windowInSecondary->assertNoEvents();
3955
3956 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003958 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003959 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003960 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003961
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003962 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003963 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003964
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003965 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003966 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3967 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003968
3969 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003970 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003971 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003972 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003973 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003974 windowInSecondary->assertNoEvents();
3975}
3976
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003977// Test per-display input monitors for motion event.
3978TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003979 FakeMonitorReceiver monitorInPrimary =
3980 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3981 FakeMonitorReceiver monitorInSecondary =
3982 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003983
3984 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3986 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003988 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003989 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003990 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003991 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003992
3993 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3995 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3996 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003997 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003998 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003999 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004000 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004001
4002 // Test inject a non-pointer motion event.
4003 // If specific a display, it will dispatch to the focused window of particular display,
4004 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4006 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004008 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004009 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004010 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004011 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004012}
4013
4014// Test per-display input monitors for key event.
4015TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004016 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004017 FakeMonitorReceiver monitorInPrimary =
4018 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4019 FakeMonitorReceiver monitorInSecondary =
4020 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004021
4022 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4024 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004025 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004026 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004027 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004028 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004029}
4030
Vishnu Nair958da932020-08-21 17:12:37 -07004031TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4032 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004033 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004034 secondWindowInPrimary->setFocusable(true);
4035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4036 setFocusedWindow(secondWindowInPrimary);
4037 windowInPrimary->consumeFocusEvent(false);
4038 secondWindowInPrimary->consumeFocusEvent(true);
4039
4040 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4042 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004043 windowInPrimary->assertNoEvents();
4044 windowInSecondary->assertNoEvents();
4045 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4046}
4047
Arthur Hungdfd528e2021-12-08 13:23:04 +00004048TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4049 FakeMonitorReceiver monitorInPrimary =
4050 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4051 FakeMonitorReceiver monitorInSecondary =
4052 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4053
4054 // Test touch down on primary display.
4055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4056 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4058 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4059 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4060
4061 // Test touch down on second display.
4062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4063 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4064 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4065 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4066 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4067
4068 // Trigger cancel touch.
4069 mDispatcher->cancelCurrentTouch();
4070 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4071 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4072 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4073 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4074
4075 // Test inject a move motion event, no window/monitor should receive the event.
4076 ASSERT_EQ(InputEventInjectionResult::FAILED,
4077 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4078 ADISPLAY_ID_DEFAULT, {110, 200}))
4079 << "Inject motion event should return InputEventInjectionResult::FAILED";
4080 windowInPrimary->assertNoEvents();
4081 monitorInPrimary.assertNoEvents();
4082
4083 ASSERT_EQ(InputEventInjectionResult::FAILED,
4084 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4085 SECOND_DISPLAY_ID, {110, 200}))
4086 << "Inject motion event should return InputEventInjectionResult::FAILED";
4087 windowInSecondary->assertNoEvents();
4088 monitorInSecondary.assertNoEvents();
4089}
4090
Jackal Guof9696682018-10-05 12:23:23 +08004091class InputFilterTest : public InputDispatcherTest {
4092protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004093 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4094 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004095 NotifyMotionArgs motionArgs;
4096
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004097 motionArgs =
4098 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004099 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004100 motionArgs =
4101 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004102 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004103 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004104 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004105 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4106 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004107 } else {
4108 mFakePolicy->assertFilterInputEventWasNotCalled();
4109 }
4110 }
4111
4112 void testNotifyKey(bool expectToBeFiltered) {
4113 NotifyKeyArgs keyArgs;
4114
4115 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4116 mDispatcher->notifyKey(&keyArgs);
4117 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4118 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004119 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004120
4121 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004122 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004123 } else {
4124 mFakePolicy->assertFilterInputEventWasNotCalled();
4125 }
4126 }
4127};
4128
4129// Test InputFilter for MotionEvent
4130TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4131 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4132 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4133 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4134
4135 // Enable InputFilter
4136 mDispatcher->setInputFilterEnabled(true);
4137 // Test touch on both primary and second display, and check if both events are filtered.
4138 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4139 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4140
4141 // Disable InputFilter
4142 mDispatcher->setInputFilterEnabled(false);
4143 // Test touch on both primary and second display, and check if both events aren't filtered.
4144 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4145 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4146}
4147
4148// Test InputFilter for KeyEvent
4149TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4150 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4151 testNotifyKey(/*expectToBeFiltered*/ false);
4152
4153 // Enable InputFilter
4154 mDispatcher->setInputFilterEnabled(true);
4155 // Send a key event, and check if it is filtered.
4156 testNotifyKey(/*expectToBeFiltered*/ true);
4157
4158 // Disable InputFilter
4159 mDispatcher->setInputFilterEnabled(false);
4160 // Send a key event, and check if it isn't filtered.
4161 testNotifyKey(/*expectToBeFiltered*/ false);
4162}
4163
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004164// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4165// logical display coordinate space.
4166TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4167 ui::Transform firstDisplayTransform;
4168 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4169 ui::Transform secondDisplayTransform;
4170 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4171
4172 std::vector<gui::DisplayInfo> displayInfos(2);
4173 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4174 displayInfos[0].transform = firstDisplayTransform;
4175 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4176 displayInfos[1].transform = secondDisplayTransform;
4177
4178 mDispatcher->onWindowInfosChanged({}, displayInfos);
4179
4180 // Enable InputFilter
4181 mDispatcher->setInputFilterEnabled(true);
4182
4183 // Ensure the correct transforms are used for the displays.
4184 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4185 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4186}
4187
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004188class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4189protected:
4190 virtual void SetUp() override {
4191 InputDispatcherTest::SetUp();
4192
4193 /**
4194 * We don't need to enable input filter to test the injected event policy, but we enabled it
4195 * here to make the tests more realistic, since this policy only matters when inputfilter is
4196 * on.
4197 */
4198 mDispatcher->setInputFilterEnabled(true);
4199
4200 std::shared_ptr<InputApplicationHandle> application =
4201 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004202 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4203 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004204
4205 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4206 mWindow->setFocusable(true);
4207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4208 setFocusedWindow(mWindow);
4209 mWindow->consumeFocusEvent(true);
4210 }
4211
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004212 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4213 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004214 KeyEvent event;
4215
4216 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4217 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4218 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4219 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4220 const int32_t additionalPolicyFlags =
4221 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004223 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004224 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4225 policyFlags | additionalPolicyFlags));
4226
4227 InputEvent* received = mWindow->consume();
4228 ASSERT_NE(nullptr, received);
4229 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004230 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4231 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4232 ASSERT_EQ(flags, keyEvent.getFlags());
4233 }
4234
4235 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4236 int32_t flags) {
4237 MotionEvent event;
4238 PointerProperties pointerProperties[1];
4239 PointerCoords pointerCoords[1];
4240 pointerProperties[0].clear();
4241 pointerProperties[0].id = 0;
4242 pointerCoords[0].clear();
4243 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4244 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4245
4246 ui::Transform identityTransform;
4247 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4248 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4249 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4250 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4251 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004252 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004253 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004254 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4255
4256 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004258 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004259 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4260 policyFlags | additionalPolicyFlags));
4261
4262 InputEvent* received = mWindow->consume();
4263 ASSERT_NE(nullptr, received);
4264 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4265 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4266 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4267 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004268 }
4269
4270private:
4271 sp<FakeWindowHandle> mWindow;
4272};
4273
4274TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004275 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4276 // filter. Without it, the event will no different from a regularly injected event, and the
4277 // injected device id will be overwritten.
4278 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4279 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004280}
4281
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004282TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004283 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004284 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4285 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4286}
4287
4288TEST_F(InputFilterInjectionPolicyTest,
4289 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4290 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4291 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4292 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004293}
4294
4295TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4296 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004297 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004298}
4299
chaviwfd6d3512019-03-25 13:23:49 -07004300class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004301 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004302 InputDispatcherTest::SetUp();
4303
Chris Yea209fde2020-07-22 13:54:51 -07004304 std::shared_ptr<FakeApplicationHandle> application =
4305 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004306 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004307 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004308 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004309
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004310 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004311 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004312 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004313
4314 // Set focused application.
4315 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004316 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004317
4318 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004320 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004321 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004322 }
4323
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004324 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004325 InputDispatcherTest::TearDown();
4326
4327 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004328 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004329 }
4330
4331protected:
4332 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004333 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004334 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004335};
4336
4337// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4338// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4339// the onPointerDownOutsideFocus callback.
4340TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4343 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004345 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004346
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004347 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004348 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4349}
4350
4351// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4352// DOWN on the window that doesn't have focus. Ensure no window received the
4353// onPointerDownOutsideFocus callback.
4354TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004356 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004357 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004358 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004359
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004360 ASSERT_TRUE(mDispatcher->waitForIdle());
4361 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004362}
4363
4364// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4365// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4366TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004367 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4368 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004370 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004371
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004372 ASSERT_TRUE(mDispatcher->waitForIdle());
4373 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004374}
4375
4376// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4377// DOWN on the window that already has focus. Ensure no window received the
4378// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004379TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004380 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004381 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004382 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004384 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004385
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004386 ASSERT_TRUE(mDispatcher->waitForIdle());
4387 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004388}
4389
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004390// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4391// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4392TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4393 const MotionEvent event =
4394 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4395 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4396 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4397 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4398 .build();
4399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4400 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4401 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4402
4403 ASSERT_TRUE(mDispatcher->waitForIdle());
4404 mFakePolicy->assertOnPointerDownWasNotCalled();
4405 // Ensure that the unfocused window did not receive any FOCUS events.
4406 mUnfocusedWindow->assertNoEvents();
4407}
4408
chaviwaf87b3e2019-10-01 16:59:28 -07004409// These tests ensures we can send touch events to a single client when there are multiple input
4410// windows that point to the same client token.
4411class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4412 virtual void SetUp() override {
4413 InputDispatcherTest::SetUp();
4414
Chris Yea209fde2020-07-22 13:54:51 -07004415 std::shared_ptr<FakeApplicationHandle> application =
4416 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004417 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4418 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004419 mWindow1->setFrame(Rect(0, 0, 100, 100));
4420
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004421 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4422 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004423 mWindow2->setFrame(Rect(100, 100, 200, 200));
4424
Arthur Hung72d8dc32020-03-28 00:48:39 +00004425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004426 }
4427
4428protected:
4429 sp<FakeWindowHandle> mWindow1;
4430 sp<FakeWindowHandle> mWindow2;
4431
4432 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004433 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004434 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4435 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004436 }
4437
4438 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4439 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004440 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004441 InputEvent* event = window->consume();
4442
4443 ASSERT_NE(nullptr, event) << name.c_str()
4444 << ": consumer should have returned non-NULL event.";
4445
4446 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4447 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4448 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4449
4450 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004451 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004452
4453 for (size_t i = 0; i < points.size(); i++) {
4454 float expectedX = points[i].x;
4455 float expectedY = points[i].y;
4456
4457 EXPECT_EQ(expectedX, motionEvent.getX(i))
4458 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4459 << ", got " << motionEvent.getX(i);
4460 EXPECT_EQ(expectedY, motionEvent.getY(i))
4461 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4462 << ", got " << motionEvent.getY(i);
4463 }
4464 }
chaviw9eaa22c2020-07-01 16:21:27 -07004465
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004466 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004467 std::vector<PointF> expectedPoints) {
4468 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4469 ADISPLAY_ID_DEFAULT, touchedPoints);
4470 mDispatcher->notifyMotion(&motionArgs);
4471
4472 // Always consume from window1 since it's the window that has the InputReceiver
4473 consumeMotionEvent(mWindow1, action, expectedPoints);
4474 }
chaviwaf87b3e2019-10-01 16:59:28 -07004475};
4476
4477TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4478 // Touch Window 1
4479 PointF touchedPoint = {10, 10};
4480 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004481 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004482
4483 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004484 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004485
4486 // Touch Window 2
4487 touchedPoint = {150, 150};
4488 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004489 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004490}
4491
chaviw9eaa22c2020-07-01 16:21:27 -07004492TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4493 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004494 mWindow2->setWindowScale(0.5f, 0.5f);
4495
4496 // Touch Window 1
4497 PointF touchedPoint = {10, 10};
4498 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004499 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004500 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004501 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004502
4503 // Touch Window 2
4504 touchedPoint = {150, 150};
4505 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004506 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4507 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004508
chaviw9eaa22c2020-07-01 16:21:27 -07004509 // Update the transform so rotation is set
4510 mWindow2->setWindowTransform(0, -1, 1, 0);
4511 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4512 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004513}
4514
chaviw9eaa22c2020-07-01 16:21:27 -07004515TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004516 mWindow2->setWindowScale(0.5f, 0.5f);
4517
4518 // Touch Window 1
4519 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4520 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004521 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004522
4523 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004524 touchedPoints.push_back(PointF{150, 150});
4525 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004526 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004527
chaviw9eaa22c2020-07-01 16:21:27 -07004528 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004529 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004530 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004531
chaviw9eaa22c2020-07-01 16:21:27 -07004532 // Update the transform so rotation is set for Window 2
4533 mWindow2->setWindowTransform(0, -1, 1, 0);
4534 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004535 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004536}
4537
chaviw9eaa22c2020-07-01 16:21:27 -07004538TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004539 mWindow2->setWindowScale(0.5f, 0.5f);
4540
4541 // Touch Window 1
4542 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4543 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004544 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004545
4546 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004547 touchedPoints.push_back(PointF{150, 150});
4548 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004549
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004550 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004551
4552 // Move both windows
4553 touchedPoints = {{20, 20}, {175, 175}};
4554 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4555 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4556
chaviw9eaa22c2020-07-01 16:21:27 -07004557 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004558
chaviw9eaa22c2020-07-01 16:21:27 -07004559 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004560 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004561 expectedPoints.pop_back();
4562
4563 // Touch Window 2
4564 mWindow2->setWindowTransform(0, -1, 1, 0);
4565 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004566 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004567
4568 // Move both windows
4569 touchedPoints = {{20, 20}, {175, 175}};
4570 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4571 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4572
4573 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004574}
4575
4576TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4577 mWindow1->setWindowScale(0.5f, 0.5f);
4578
4579 // Touch Window 1
4580 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4581 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004582 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004583
4584 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004585 touchedPoints.push_back(PointF{150, 150});
4586 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004587
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004588 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004589
4590 // Move both windows
4591 touchedPoints = {{20, 20}, {175, 175}};
4592 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4593 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4594
chaviw9eaa22c2020-07-01 16:21:27 -07004595 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004596}
4597
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004598class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4599 virtual void SetUp() override {
4600 InputDispatcherTest::SetUp();
4601
Chris Yea209fde2020-07-22 13:54:51 -07004602 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004603 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004604 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4605 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004606 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004607 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004608 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004609
4610 // Set focused application.
4611 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4612
4613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004614 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004615 mWindow->consumeFocusEvent(true);
4616 }
4617
4618 virtual void TearDown() override {
4619 InputDispatcherTest::TearDown();
4620 mWindow.clear();
4621 }
4622
4623protected:
Chris Yea209fde2020-07-22 13:54:51 -07004624 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004625 sp<FakeWindowHandle> mWindow;
4626 static constexpr PointF WINDOW_LOCATION = {20, 20};
4627
4628 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4631 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004633 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4634 WINDOW_LOCATION));
4635 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004636
4637 sp<FakeWindowHandle> addSpyWindow() {
4638 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004639 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004640 spy->setTrustedOverlay(true);
4641 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004642 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004643 spy->setDispatchingTimeout(30ms);
4644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4645 return spy;
4646 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004647};
4648
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649// Send a tap and respond, which should not cause an ANR.
4650TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4651 tapOnWindow();
4652 mWindow->consumeMotionDown();
4653 mWindow->consumeMotionUp();
4654 ASSERT_TRUE(mDispatcher->waitForIdle());
4655 mFakePolicy->assertNotifyAnrWasNotCalled();
4656}
4657
4658// Send a regular key and respond, which should not cause an ANR.
4659TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4662 ASSERT_TRUE(mDispatcher->waitForIdle());
4663 mFakePolicy->assertNotifyAnrWasNotCalled();
4664}
4665
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004666TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4667 mWindow->setFocusable(false);
4668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4669 mWindow->consumeFocusEvent(false);
4670
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004671 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004672 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004673 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4674 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004676 // Key will not go to window because we have no focused window.
4677 // The 'no focused window' ANR timer should start instead.
4678
4679 // Now, the focused application goes away.
4680 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4681 // The key should get dropped and there should be no ANR.
4682
4683 ASSERT_TRUE(mDispatcher->waitForIdle());
4684 mFakePolicy->assertNotifyAnrWasNotCalled();
4685}
4686
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004687// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4689// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004690TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004692 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4693 WINDOW_LOCATION));
4694
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004695 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4696 ASSERT_TRUE(sequenceNum);
4697 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004698 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004699
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 mWindow->finishEvent(*sequenceNum);
4701 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4702 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004703 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004704 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004705}
4706
4707// Send a key to the app and have the app not respond right away.
4708TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4709 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004711 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4712 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004713 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004714 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004715 ASSERT_TRUE(mDispatcher->waitForIdle());
4716}
4717
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718// We have a focused application, but no focused window
4719TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004720 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4722 mWindow->consumeFocusEvent(false);
4723
4724 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4727 WINDOW_LOCATION));
4728 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4729 mDispatcher->waitForIdle();
4730 mFakePolicy->assertNotifyAnrWasNotCalled();
4731
4732 // Once a focused event arrives, we get an ANR for this application
4733 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4734 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004735 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004737 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Vishnu Naire4df8752022-09-08 09:17:55 -07004740 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741 ASSERT_TRUE(mDispatcher->waitForIdle());
4742}
4743
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004744/**
4745 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4746 * there will not be an ANR.
4747 */
4748TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4749 mWindow->setFocusable(false);
4750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4751 mWindow->consumeFocusEvent(false);
4752
4753 KeyEvent event;
4754 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4755 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4756
4757 // Define a valid key down event that is stale (too old).
4758 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4759 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4760 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4761
4762 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4763
4764 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004765 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004766 InputEventInjectionSync::WAIT_FOR_RESULT,
4767 INJECT_EVENT_TIMEOUT, policyFlags);
4768 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4769 << "Injection should fail because the event is stale";
4770
4771 ASSERT_TRUE(mDispatcher->waitForIdle());
4772 mFakePolicy->assertNotifyAnrWasNotCalled();
4773 mWindow->assertNoEvents();
4774}
4775
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004777// Make sure that we don't notify policy twice about the same ANR.
4778TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004779 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4781 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004782
4783 // Once a focused event arrives, we get an ANR for this application
4784 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4785 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004786 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004787 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004788 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004789 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Vishnu Naire4df8752022-09-08 09:17:55 -07004790 const std::chrono::duration appTimeout =
4791 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4792 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793
Vishnu Naire4df8752022-09-08 09:17:55 -07004794 std::this_thread::sleep_for(appTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004795 // ANR should not be raised again. It is up to policy to do that if it desires.
4796 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004798 // If we now get a focused window, the ANR should stop, but the policy handles that via
4799 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800 ASSERT_TRUE(mDispatcher->waitForIdle());
4801}
4802
4803// We have a focused application, but no focused window
4804TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004805 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4807 mWindow->consumeFocusEvent(false);
4808
4809 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004812 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4813 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814
Vishnu Naire4df8752022-09-08 09:17:55 -07004815 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4816 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817
4818 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004819 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820 ASSERT_TRUE(mDispatcher->waitForIdle());
4821 mWindow->assertNoEvents();
4822}
4823
4824/**
4825 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4826 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4827 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4828 * the ANR mechanism should still work.
4829 *
4830 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4831 * DOWN event, while not responding on the second one.
4832 */
4833TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4834 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4835 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4836 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4837 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4838 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004839 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840
4841 // Now send ACTION_UP, with identical timestamp
4842 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4843 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4844 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4845 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004846 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847
4848 // We have now sent down and up. Let's consume first event and then ANR on the second.
4849 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4850 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004851 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852}
4853
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004854// A spy window can receive an ANR
4855TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4856 sp<FakeWindowHandle> spy = addSpyWindow();
4857
4858 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4859 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4860 WINDOW_LOCATION));
4861 mWindow->consumeMotionDown();
4862
4863 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4864 ASSERT_TRUE(sequenceNum);
4865 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004866 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004867
4868 spy->finishEvent(*sequenceNum);
4869 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4870 0 /*flags*/);
4871 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004872 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004873}
4874
4875// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004877TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4878 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004880 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4881 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884
4885 // Stuck on the ACTION_UP
4886 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004887 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004889 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004891 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4892 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004893
4894 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4895 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004896 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004897 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004898 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899}
4900
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004901// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004903TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4904 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905
4906 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004907 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4908 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004909
4910 mWindow->consumeMotionDown();
4911 // Stuck on the ACTION_UP
4912 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004913 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004915 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004917 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4918 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919
4920 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4921 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004922 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004924 spy->assertNoEvents();
4925}
4926
4927TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4928 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4929
4930 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4931
4932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4933 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4934 WINDOW_LOCATION));
4935
4936 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4937 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4938 ASSERT_TRUE(consumeSeq);
4939
Prabir Pradhanedd96402022-02-15 01:46:16 -08004940 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004941
4942 monitor.finishEvent(*consumeSeq);
4943 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4944
4945 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004946 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004947}
4948
4949// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4950// process events, you don't get an anr. When the window later becomes unresponsive again, you
4951// get an ANR again.
4952// 1. tap -> block on ACTION_UP -> receive ANR
4953// 2. consume all pending events (= queue becomes healthy again)
4954// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4955TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4956 tapOnWindow();
4957
4958 mWindow->consumeMotionDown();
4959 // Block on ACTION_UP
4960 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004961 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4963 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004964 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965 mWindow->assertNoEvents();
4966
4967 tapOnWindow();
4968 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004969 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004970 mWindow->consumeMotionUp();
4971
4972 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004973 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004974 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 mWindow->assertNoEvents();
4976}
4977
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004978// If a connection remains unresponsive for a while, make sure policy is only notified once about
4979// it.
4980TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004982 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4983 WINDOW_LOCATION));
4984
4985 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004986 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004987 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004988 // 'notifyConnectionUnresponsive' should only be called once per connection
4989 mFakePolicy->assertNotifyAnrWasNotCalled();
4990 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991 mWindow->consumeMotionDown();
4992 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4993 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4994 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004995 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004996 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004997 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004998}
4999
5000/**
5001 * If a window is processing a motion event, and then a key event comes in, the key event should
5002 * not to to the focused window until the motion is processed.
5003 *
5004 * Warning!!!
5005 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5006 * and the injection timeout that we specify when injecting the key.
5007 * We must have the injection timeout (10ms) be smaller than
5008 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5009 *
5010 * If that value changes, this test should also change.
5011 */
5012TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5013 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5015
5016 tapOnWindow();
5017 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5018 ASSERT_TRUE(downSequenceNum);
5019 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5020 ASSERT_TRUE(upSequenceNum);
5021 // Don't finish the events yet, and send a key
5022 // Injection will "succeed" because we will eventually give up and send the key to the focused
5023 // window even if motions are still being processed. But because the injection timeout is short,
5024 // we will receive INJECTION_TIMED_OUT as the result.
5025
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005026 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005027 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005028 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5029 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005030 // Key will not be sent to the window, yet, because the window is still processing events
5031 // and the key remains pending, waiting for the touch events to be processed
5032 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5033 ASSERT_FALSE(keySequenceNum);
5034
5035 std::this_thread::sleep_for(500ms);
5036 // if we wait long enough though, dispatcher will give up, and still send the key
5037 // to the focused window, even though we have not yet finished the motion event
5038 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5039 mWindow->finishEvent(*downSequenceNum);
5040 mWindow->finishEvent(*upSequenceNum);
5041}
5042
5043/**
5044 * If a window is processing a motion event, and then a key event comes in, the key event should
5045 * not go to the focused window until the motion is processed.
5046 * If then a new motion comes in, then the pending key event should be going to the currently
5047 * focused window right away.
5048 */
5049TEST_F(InputDispatcherSingleWindowAnr,
5050 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5051 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5053
5054 tapOnWindow();
5055 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5056 ASSERT_TRUE(downSequenceNum);
5057 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5058 ASSERT_TRUE(upSequenceNum);
5059 // Don't finish the events yet, and send a key
5060 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005062 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005063 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005064 // At this point, key is still pending, and should not be sent to the application yet.
5065 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5066 ASSERT_FALSE(keySequenceNum);
5067
5068 // Now tap down again. It should cause the pending key to go to the focused window right away.
5069 tapOnWindow();
5070 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5071 // the other events yet. We can finish events in any order.
5072 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5073 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5074 mWindow->consumeMotionDown();
5075 mWindow->consumeMotionUp();
5076 mWindow->assertNoEvents();
5077}
5078
5079class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5080 virtual void SetUp() override {
5081 InputDispatcherTest::SetUp();
5082
Chris Yea209fde2020-07-22 13:54:51 -07005083 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005084 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005085 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5086 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005087 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005089 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005091 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5092 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005093 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005095
5096 // Set focused application.
5097 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005098 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005099
5100 // Expect one focus window exist in display.
5101 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005102 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005103 mFocusedWindow->consumeFocusEvent(true);
5104 }
5105
5106 virtual void TearDown() override {
5107 InputDispatcherTest::TearDown();
5108
5109 mUnfocusedWindow.clear();
5110 mFocusedWindow.clear();
5111 }
5112
5113protected:
Chris Yea209fde2020-07-22 13:54:51 -07005114 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005115 sp<FakeWindowHandle> mUnfocusedWindow;
5116 sp<FakeWindowHandle> mFocusedWindow;
5117 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5118 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5119 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5120
5121 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5122
5123 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5124
5125private:
5126 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005127 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005128 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5129 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005130 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5132 location));
5133 }
5134};
5135
5136// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5137// should be ANR'd first.
5138TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5141 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005142 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005143 mFocusedWindow->consumeMotionDown();
5144 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5145 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5146 // We consumed all events, so no ANR
5147 ASSERT_TRUE(mDispatcher->waitForIdle());
5148 mFakePolicy->assertNotifyAnrWasNotCalled();
5149
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005151 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5152 FOCUSED_WINDOW_LOCATION));
5153 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5154 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005155
5156 const std::chrono::duration timeout =
5157 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005158 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005159 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5160 // sequence to make it consistent
5161 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005162 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005163 mFocusedWindow->consumeMotionDown();
5164 // This cancel is generated because the connection was unresponsive
5165 mFocusedWindow->consumeMotionCancel();
5166 mFocusedWindow->assertNoEvents();
5167 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005168 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005169 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5170 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005171 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005172}
5173
5174// If we have 2 windows with identical timeouts that are both unresponsive,
5175// it doesn't matter which order they should have ANR.
5176// But we should receive ANR for both.
5177TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5178 // Set the timeout for unfocused window to match the focused window
5179 mUnfocusedWindow->setDispatchingTimeout(10ms);
5180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5181
5182 tapOnFocusedWindow();
5183 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005184 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5185 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5186 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005187
5188 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005189 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5190 mFocusedWindow->getToken() == anrConnectionToken2);
5191 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5192 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005193
5194 ASSERT_TRUE(mDispatcher->waitForIdle());
5195 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005196
5197 mFocusedWindow->consumeMotionDown();
5198 mFocusedWindow->consumeMotionUp();
5199 mUnfocusedWindow->consumeMotionOutside();
5200
Prabir Pradhanedd96402022-02-15 01:46:16 -08005201 sp<IBinder> responsiveToken1, responsiveToken2;
5202 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5203 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005204
5205 // Both applications should be marked as responsive, in any order
5206 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5207 mFocusedWindow->getToken() == responsiveToken2);
5208 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5209 mUnfocusedWindow->getToken() == responsiveToken2);
5210 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211}
5212
5213// If a window is already not responding, the second tap on the same window should be ignored.
5214// We should also log an error to account for the dropped event (not tested here).
5215// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5216TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5217 tapOnFocusedWindow();
5218 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5219 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5220 // Receive the events, but don't respond
5221 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5222 ASSERT_TRUE(downEventSequenceNum);
5223 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5224 ASSERT_TRUE(upEventSequenceNum);
5225 const std::chrono::duration timeout =
5226 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005227 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005228
5229 // Tap once again
5230 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005231 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005232 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5233 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005234 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005235 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5236 FOCUSED_WINDOW_LOCATION));
5237 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5238 // valid touch target
5239 mUnfocusedWindow->assertNoEvents();
5240
5241 // Consume the first tap
5242 mFocusedWindow->finishEvent(*downEventSequenceNum);
5243 mFocusedWindow->finishEvent(*upEventSequenceNum);
5244 ASSERT_TRUE(mDispatcher->waitForIdle());
5245 // The second tap did not go to the focused window
5246 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005247 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005248 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5249 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005250 mFakePolicy->assertNotifyAnrWasNotCalled();
5251}
5252
5253// If you tap outside of all windows, there will not be ANR
5254TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005255 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005256 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5257 LOCATION_OUTSIDE_ALL_WINDOWS));
5258 ASSERT_TRUE(mDispatcher->waitForIdle());
5259 mFakePolicy->assertNotifyAnrWasNotCalled();
5260}
5261
5262// Since the focused window is paused, tapping on it should not produce any events
5263TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5264 mFocusedWindow->setPaused(true);
5265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5266
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005267 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005268 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5269 FOCUSED_WINDOW_LOCATION));
5270
5271 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5272 ASSERT_TRUE(mDispatcher->waitForIdle());
5273 // Should not ANR because the window is paused, and touches shouldn't go to it
5274 mFakePolicy->assertNotifyAnrWasNotCalled();
5275
5276 mFocusedWindow->assertNoEvents();
5277 mUnfocusedWindow->assertNoEvents();
5278}
5279
5280/**
5281 * If a window is processing a motion event, and then a key event comes in, the key event should
5282 * not to to the focused window until the motion is processed.
5283 * If a different window becomes focused at this time, the key should go to that window instead.
5284 *
5285 * Warning!!!
5286 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5287 * and the injection timeout that we specify when injecting the key.
5288 * We must have the injection timeout (10ms) be smaller than
5289 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5290 *
5291 * If that value changes, this test should also change.
5292 */
5293TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5294 // Set a long ANR timeout to prevent it from triggering
5295 mFocusedWindow->setDispatchingTimeout(2s);
5296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5297
5298 tapOnUnfocusedWindow();
5299 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5300 ASSERT_TRUE(downSequenceNum);
5301 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5302 ASSERT_TRUE(upSequenceNum);
5303 // Don't finish the events yet, and send a key
5304 // Injection will succeed because we will eventually give up and send the key to the focused
5305 // window even if motions are still being processed.
5306
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005307 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005308 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005309 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005311 // Key will not be sent to the window, yet, because the window is still processing events
5312 // and the key remains pending, waiting for the touch events to be processed
5313 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5314 ASSERT_FALSE(keySequenceNum);
5315
5316 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005317 mFocusedWindow->setFocusable(false);
5318 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005320 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005321
5322 // Focus events should precede the key events
5323 mUnfocusedWindow->consumeFocusEvent(true);
5324 mFocusedWindow->consumeFocusEvent(false);
5325
5326 // Finish the tap events, which should unblock dispatcher
5327 mUnfocusedWindow->finishEvent(*downSequenceNum);
5328 mUnfocusedWindow->finishEvent(*upSequenceNum);
5329
5330 // Now that all queues are cleared and no backlog in the connections, the key event
5331 // can finally go to the newly focused "mUnfocusedWindow".
5332 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5333 mFocusedWindow->assertNoEvents();
5334 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005335 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005336}
5337
5338// When the touch stream is split across 2 windows, and one of them does not respond,
5339// then ANR should be raised and the touch should be canceled for the unresponsive window.
5340// The other window should not be affected by that.
5341TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5342 // Touch Window 1
5343 NotifyMotionArgs motionArgs =
5344 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5345 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5346 mDispatcher->notifyMotion(&motionArgs);
5347 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5348 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5349
5350 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005351 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5352 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005353 mDispatcher->notifyMotion(&motionArgs);
5354
5355 const std::chrono::duration timeout =
5356 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005357 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005358
5359 mUnfocusedWindow->consumeMotionDown();
5360 mFocusedWindow->consumeMotionDown();
5361 // Focused window may or may not receive ACTION_MOVE
5362 // But it should definitely receive ACTION_CANCEL due to the ANR
5363 InputEvent* event;
5364 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5365 ASSERT_TRUE(moveOrCancelSequenceNum);
5366 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5367 ASSERT_NE(nullptr, event);
5368 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5369 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5370 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5371 mFocusedWindow->consumeMotionCancel();
5372 } else {
5373 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5374 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005375 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005376 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5377 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005378
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005379 mUnfocusedWindow->assertNoEvents();
5380 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005381 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005382}
5383
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005384/**
5385 * If we have no focused window, and a key comes in, we start the ANR timer.
5386 * The focused application should add a focused window before the timer runs out to prevent ANR.
5387 *
5388 * If the user touches another application during this time, the key should be dropped.
5389 * Next, if a new focused window comes in, without toggling the focused application,
5390 * then no ANR should occur.
5391 *
5392 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5393 * but in some cases the policy may not update the focused application.
5394 */
5395TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5396 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5397 std::make_shared<FakeApplicationHandle>();
5398 focusedApplication->setDispatchingTimeout(60ms);
5399 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5400 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5401 mFocusedWindow->setFocusable(false);
5402
5403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5404 mFocusedWindow->consumeFocusEvent(false);
5405
5406 // Send a key. The ANR timer should start because there is no focused window.
5407 // 'focusedApplication' will get blamed if this timer completes.
5408 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005409 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005410 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005411 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5412 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005414
5415 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5416 // then the injected touches won't cause the focused event to get dropped.
5417 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5418 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5419 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5420 // For this test, it means that the key would get delivered to the window once it becomes
5421 // focused.
5422 std::this_thread::sleep_for(10ms);
5423
5424 // Touch unfocused window. This should force the pending key to get dropped.
5425 NotifyMotionArgs motionArgs =
5426 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5427 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5428 mDispatcher->notifyMotion(&motionArgs);
5429
5430 // We do not consume the motion right away, because that would require dispatcher to first
5431 // process (== drop) the key event, and by that time, ANR will be raised.
5432 // Set the focused window first.
5433 mFocusedWindow->setFocusable(true);
5434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5435 setFocusedWindow(mFocusedWindow);
5436 mFocusedWindow->consumeFocusEvent(true);
5437 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5438 // to another application. This could be a bug / behaviour in the policy.
5439
5440 mUnfocusedWindow->consumeMotionDown();
5441
5442 ASSERT_TRUE(mDispatcher->waitForIdle());
5443 // Should not ANR because we actually have a focused window. It was just added too slowly.
5444 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5445}
5446
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005447// These tests ensure we cannot send touch events to a window that's positioned behind a window
5448// that has feature NO_INPUT_CHANNEL.
5449// Layout:
5450// Top (closest to user)
5451// mNoInputWindow (above all windows)
5452// mBottomWindow
5453// Bottom (furthest from user)
5454class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5455 virtual void SetUp() override {
5456 InputDispatcherTest::SetUp();
5457
5458 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005459 mNoInputWindow =
5460 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5461 "Window without input channel", ADISPLAY_ID_DEFAULT,
5462 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005463 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005464 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5465 // It's perfectly valid for this window to not have an associated input channel
5466
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005467 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5468 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005469 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5470
5471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5472 }
5473
5474protected:
5475 std::shared_ptr<FakeApplicationHandle> mApplication;
5476 sp<FakeWindowHandle> mNoInputWindow;
5477 sp<FakeWindowHandle> mBottomWindow;
5478};
5479
5480TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5481 PointF touchedPoint = {10, 10};
5482
5483 NotifyMotionArgs motionArgs =
5484 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5485 ADISPLAY_ID_DEFAULT, {touchedPoint});
5486 mDispatcher->notifyMotion(&motionArgs);
5487
5488 mNoInputWindow->assertNoEvents();
5489 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5490 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5491 // and therefore should prevent mBottomWindow from receiving touches
5492 mBottomWindow->assertNoEvents();
5493}
5494
5495/**
5496 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5497 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5498 */
5499TEST_F(InputDispatcherMultiWindowOcclusionTests,
5500 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005501 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5502 "Window with input channel and NO_INPUT_CHANNEL",
5503 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005504
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005505 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005506 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5508
5509 PointF touchedPoint = {10, 10};
5510
5511 NotifyMotionArgs motionArgs =
5512 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5513 ADISPLAY_ID_DEFAULT, {touchedPoint});
5514 mDispatcher->notifyMotion(&motionArgs);
5515
5516 mNoInputWindow->assertNoEvents();
5517 mBottomWindow->assertNoEvents();
5518}
5519
Vishnu Nair958da932020-08-21 17:12:37 -07005520class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5521protected:
5522 std::shared_ptr<FakeApplicationHandle> mApp;
5523 sp<FakeWindowHandle> mWindow;
5524 sp<FakeWindowHandle> mMirror;
5525
5526 virtual void SetUp() override {
5527 InputDispatcherTest::SetUp();
5528 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005529 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5530 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5531 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005532 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5533 mWindow->setFocusable(true);
5534 mMirror->setFocusable(true);
5535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5536 }
5537};
5538
5539TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5540 // Request focus on a mirrored window
5541 setFocusedWindow(mMirror);
5542
5543 // window gets focused
5544 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5546 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005547 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5548}
5549
5550// A focused & mirrored window remains focused only if the window and its mirror are both
5551// focusable.
5552TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5553 setFocusedWindow(mMirror);
5554
5555 // window gets focused
5556 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5558 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005559 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5561 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005562 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5563
5564 mMirror->setFocusable(false);
5565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5566
5567 // window loses focus since one of the windows associated with the token in not focusable
5568 mWindow->consumeFocusEvent(false);
5569
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005570 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5571 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005572 mWindow->assertNoEvents();
5573}
5574
5575// A focused & mirrored window remains focused until the window and its mirror both become
5576// invisible.
5577TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
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);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5586 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005587 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5588
5589 mMirror->setVisible(false);
5590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5591
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005592 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5593 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005594 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005595 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5596 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005597 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5598
5599 mWindow->setVisible(false);
5600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5601
5602 // window loses focus only after all windows associated with the token become invisible.
5603 mWindow->consumeFocusEvent(false);
5604
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005605 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5606 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005607 mWindow->assertNoEvents();
5608}
5609
5610// A focused & mirrored window remains focused until both windows are removed.
5611TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5612 setFocusedWindow(mMirror);
5613
5614 // window gets focused
5615 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5617 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005618 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005619 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5620 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005621 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5622
5623 // single window is removed but the window token remains focused
5624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5625
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5627 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005628 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5630 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005631 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5632
5633 // Both windows are removed
5634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5635 mWindow->consumeFocusEvent(false);
5636
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005637 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5638 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005639 mWindow->assertNoEvents();
5640}
5641
5642// Focus request can be pending until one window becomes visible.
5643TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5644 // Request focus on an invisible mirror.
5645 mWindow->setVisible(false);
5646 mMirror->setVisible(false);
5647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5648 setFocusedWindow(mMirror);
5649
5650 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005652 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005653 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005654
5655 mMirror->setVisible(true);
5656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5657
5658 // window gets focused
5659 mWindow->consumeFocusEvent(true);
5660 // window gets the pending key event
5661 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5662}
Prabir Pradhan99987712020-11-10 18:43:05 -08005663
5664class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5665protected:
5666 std::shared_ptr<FakeApplicationHandle> mApp;
5667 sp<FakeWindowHandle> mWindow;
5668 sp<FakeWindowHandle> mSecondWindow;
5669
5670 void SetUp() override {
5671 InputDispatcherTest::SetUp();
5672 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005673 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005674 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005675 mSecondWindow =
5676 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005677 mSecondWindow->setFocusable(true);
5678
5679 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5681
5682 setFocusedWindow(mWindow);
5683 mWindow->consumeFocusEvent(true);
5684 }
5685
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005686 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5687 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005688 mDispatcher->notifyPointerCaptureChanged(&args);
5689 }
5690
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005691 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5692 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005693 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005694 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5695 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005696 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005697 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005698 }
5699};
5700
5701TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5702 // Ensure that capture cannot be obtained for unfocused windows.
5703 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5704 mFakePolicy->assertSetPointerCaptureNotCalled();
5705 mSecondWindow->assertNoEvents();
5706
5707 // Ensure that capture can be enabled from the focus window.
5708 requestAndVerifyPointerCapture(mWindow, true);
5709
5710 // Ensure that capture cannot be disabled from a window that does not have capture.
5711 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5712 mFakePolicy->assertSetPointerCaptureNotCalled();
5713
5714 // Ensure that capture can be disabled from the window with capture.
5715 requestAndVerifyPointerCapture(mWindow, false);
5716}
5717
5718TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005719 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005720
5721 setFocusedWindow(mSecondWindow);
5722
5723 // Ensure that the capture disabled event was sent first.
5724 mWindow->consumeCaptureEvent(false);
5725 mWindow->consumeFocusEvent(false);
5726 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005727 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005728
5729 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005730 notifyPointerCaptureChanged({});
5731 notifyPointerCaptureChanged(request);
5732 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005733 mWindow->assertNoEvents();
5734 mSecondWindow->assertNoEvents();
5735 mFakePolicy->assertSetPointerCaptureNotCalled();
5736}
5737
5738TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005739 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005740
5741 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005742 notifyPointerCaptureChanged({});
5743 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005744
5745 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005746 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005747 mWindow->consumeCaptureEvent(false);
5748 mWindow->assertNoEvents();
5749}
5750
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005751TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5752 requestAndVerifyPointerCapture(mWindow, true);
5753
5754 // The first window loses focus.
5755 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005756 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005757 mWindow->consumeCaptureEvent(false);
5758
5759 // Request Pointer Capture from the second window before the notification from InputReader
5760 // arrives.
5761 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005762 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005763
5764 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005765 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005766
5767 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005768 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005769
5770 mSecondWindow->consumeFocusEvent(true);
5771 mSecondWindow->consumeCaptureEvent(true);
5772}
5773
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005774TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5775 // App repeatedly enables and disables capture.
5776 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5777 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5778 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5779 mFakePolicy->assertSetPointerCaptureCalled(false);
5780 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5781 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5782
5783 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5784 // first request is now stale, this should do nothing.
5785 notifyPointerCaptureChanged(firstRequest);
5786 mWindow->assertNoEvents();
5787
5788 // InputReader notifies that the second request was enabled.
5789 notifyPointerCaptureChanged(secondRequest);
5790 mWindow->consumeCaptureEvent(true);
5791}
5792
Prabir Pradhan7092e262022-05-03 16:51:09 +00005793TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5794 requestAndVerifyPointerCapture(mWindow, true);
5795
5796 // App toggles pointer capture off and on.
5797 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5798 mFakePolicy->assertSetPointerCaptureCalled(false);
5799
5800 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5801 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5802
5803 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5804 // preceding "disable" request.
5805 notifyPointerCaptureChanged(enableRequest);
5806
5807 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5808 // any notifications.
5809 mWindow->assertNoEvents();
5810}
5811
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005812class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5813protected:
5814 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005815
5816 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5817 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5818
5819 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5820 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5821
5822 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5823 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5824 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5825 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5826 MAXIMUM_OBSCURING_OPACITY);
5827
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005828 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005829 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005830 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005831
5832 sp<FakeWindowHandle> mTouchWindow;
5833
5834 virtual void SetUp() override {
5835 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005836 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005837 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5838 }
5839
5840 virtual void TearDown() override {
5841 InputDispatcherTest::TearDown();
5842 mTouchWindow.clear();
5843 }
5844
chaviw3277faf2021-05-19 16:45:23 -05005845 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5846 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005847 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005848 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005849 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005850 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005851 return window;
5852 }
5853
5854 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5855 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5856 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005857 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005858 // Generate an arbitrary PID based on the UID
5859 window->setOwnerInfo(1777 + (uid % 10000), uid);
5860 return window;
5861 }
5862
5863 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5864 NotifyMotionArgs args =
5865 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5866 ADISPLAY_ID_DEFAULT, points);
5867 mDispatcher->notifyMotion(&args);
5868 }
5869};
5870
5871TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005872 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005873 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005875
5876 touch();
5877
5878 mTouchWindow->assertNoEvents();
5879}
5880
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005881TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005882 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5883 const sp<FakeWindowHandle>& w =
5884 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5886
5887 touch();
5888
5889 mTouchWindow->assertNoEvents();
5890}
5891
5892TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005893 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5894 const sp<FakeWindowHandle>& w =
5895 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5897
5898 touch();
5899
5900 w->assertNoEvents();
5901}
5902
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005903TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005904 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005906
5907 touch();
5908
5909 mTouchWindow->consumeAnyMotionDown();
5910}
5911
5912TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005913 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005914 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005915 w->setFrame(Rect(0, 0, 50, 50));
5916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005917
5918 touch({PointF{100, 100}});
5919
5920 mTouchWindow->consumeAnyMotionDown();
5921}
5922
5923TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005924 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005925 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5927
5928 touch();
5929
5930 mTouchWindow->consumeAnyMotionDown();
5931}
5932
5933TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5934 const sp<FakeWindowHandle>& w =
5935 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005937
5938 touch();
5939
5940 mTouchWindow->consumeAnyMotionDown();
5941}
5942
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005943TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5944 const sp<FakeWindowHandle>& w =
5945 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5947
5948 touch();
5949
5950 w->assertNoEvents();
5951}
5952
5953/**
5954 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5955 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5956 * window, the occluding window will still receive ACTION_OUTSIDE event.
5957 */
5958TEST_F(InputDispatcherUntrustedTouchesTest,
5959 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5960 const sp<FakeWindowHandle>& w =
5961 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005962 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5964
5965 touch();
5966
5967 w->consumeMotionOutside();
5968}
5969
5970TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5971 const sp<FakeWindowHandle>& w =
5972 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005973 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5975
5976 touch();
5977
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005978 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005979}
5980
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005981TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005982 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005983 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5984 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5986
5987 touch();
5988
5989 mTouchWindow->consumeAnyMotionDown();
5990}
5991
5992TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5993 const sp<FakeWindowHandle>& w =
5994 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5995 MAXIMUM_OBSCURING_OPACITY);
5996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005997
5998 touch();
5999
6000 mTouchWindow->consumeAnyMotionDown();
6001}
6002
6003TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006004 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006005 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6006 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6008
6009 touch();
6010
6011 mTouchWindow->assertNoEvents();
6012}
6013
6014TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6015 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6016 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006017 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6018 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006019 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006020 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6021 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6023
6024 touch();
6025
6026 mTouchWindow->assertNoEvents();
6027}
6028
6029TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6030 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6031 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006032 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6033 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006034 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006035 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6036 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6038
6039 touch();
6040
6041 mTouchWindow->consumeAnyMotionDown();
6042}
6043
6044TEST_F(InputDispatcherUntrustedTouchesTest,
6045 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6046 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006047 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6048 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006049 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006050 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6051 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6053
6054 touch();
6055
6056 mTouchWindow->consumeAnyMotionDown();
6057}
6058
6059TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6060 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006061 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6062 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006063 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006064 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6065 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006066 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006067
6068 touch();
6069
6070 mTouchWindow->assertNoEvents();
6071}
6072
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006073TEST_F(InputDispatcherUntrustedTouchesTest,
6074 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6075 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006076 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6077 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006078 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006079 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6080 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6082
6083 touch();
6084
6085 mTouchWindow->assertNoEvents();
6086}
6087
6088TEST_F(InputDispatcherUntrustedTouchesTest,
6089 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6090 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006091 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6092 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006093 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006094 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6095 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6097
6098 touch();
6099
6100 mTouchWindow->consumeAnyMotionDown();
6101}
6102
6103TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6104 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006105 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6106 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6108
6109 touch();
6110
6111 mTouchWindow->consumeAnyMotionDown();
6112}
6113
6114TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6115 const sp<FakeWindowHandle>& w =
6116 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6118
6119 touch();
6120
6121 mTouchWindow->consumeAnyMotionDown();
6122}
6123
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006124TEST_F(InputDispatcherUntrustedTouchesTest,
6125 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6126 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6127 const sp<FakeWindowHandle>& w =
6128 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6129 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6130
6131 touch();
6132
6133 mTouchWindow->assertNoEvents();
6134}
6135
6136TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6137 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6138 const sp<FakeWindowHandle>& w =
6139 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6141
6142 touch();
6143
6144 mTouchWindow->consumeAnyMotionDown();
6145}
6146
6147TEST_F(InputDispatcherUntrustedTouchesTest,
6148 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6149 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6150 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006151 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6152 OPACITY_ABOVE_THRESHOLD);
6153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6154
6155 touch();
6156
6157 mTouchWindow->consumeAnyMotionDown();
6158}
6159
6160TEST_F(InputDispatcherUntrustedTouchesTest,
6161 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6162 const sp<FakeWindowHandle>& w1 =
6163 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6164 OPACITY_BELOW_THRESHOLD);
6165 const sp<FakeWindowHandle>& w2 =
6166 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6167 OPACITY_BELOW_THRESHOLD);
6168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6169
6170 touch();
6171
6172 mTouchWindow->assertNoEvents();
6173}
6174
6175/**
6176 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6177 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6178 * (which alone would result in allowing touches) does not affect the blocking behavior.
6179 */
6180TEST_F(InputDispatcherUntrustedTouchesTest,
6181 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6182 const sp<FakeWindowHandle>& wB =
6183 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6184 OPACITY_BELOW_THRESHOLD);
6185 const sp<FakeWindowHandle>& wC =
6186 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6187 OPACITY_BELOW_THRESHOLD);
6188 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6189
6190 touch();
6191
6192 mTouchWindow->assertNoEvents();
6193}
6194
6195/**
6196 * This test is testing that a window from a different UID but with same application token doesn't
6197 * block the touch. Apps can share the application token for close UI collaboration for example.
6198 */
6199TEST_F(InputDispatcherUntrustedTouchesTest,
6200 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6201 const sp<FakeWindowHandle>& w =
6202 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6203 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6205
6206 touch();
6207
6208 mTouchWindow->consumeAnyMotionDown();
6209}
6210
arthurhungb89ccb02020-12-30 16:19:01 +08006211class InputDispatcherDragTests : public InputDispatcherTest {
6212protected:
6213 std::shared_ptr<FakeApplicationHandle> mApp;
6214 sp<FakeWindowHandle> mWindow;
6215 sp<FakeWindowHandle> mSecondWindow;
6216 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006217 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006218 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6219 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006220
6221 void SetUp() override {
6222 InputDispatcherTest::SetUp();
6223 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006224 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006225 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006226
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006227 mSecondWindow =
6228 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006229 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006230
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006231 mSpyWindow =
6232 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006233 mSpyWindow->setSpy(true);
6234 mSpyWindow->setTrustedOverlay(true);
6235 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6236
arthurhungb89ccb02020-12-30 16:19:01 +08006237 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006239 }
6240
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006241 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6242 switch (fromSource) {
6243 case AINPUT_SOURCE_TOUCHSCREEN:
6244 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6245 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6246 ADISPLAY_ID_DEFAULT, {50, 50}))
6247 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6248 break;
6249 case AINPUT_SOURCE_STYLUS:
6250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6251 injectMotionEvent(
6252 mDispatcher,
6253 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6254 AINPUT_SOURCE_STYLUS)
6255 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6256 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6257 .x(50)
6258 .y(50))
6259 .build()));
6260 break;
6261 case AINPUT_SOURCE_MOUSE:
6262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6263 injectMotionEvent(
6264 mDispatcher,
6265 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6266 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6267 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6268 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6269 .x(50)
6270 .y(50))
6271 .build()));
6272 break;
6273 default:
6274 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6275 }
arthurhungb89ccb02020-12-30 16:19:01 +08006276
6277 // Window should receive motion event.
6278 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006279 // Spy window should also receive motion event
6280 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006281 }
6282
6283 // Start performing drag, we will create a drag window and transfer touch to it.
6284 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6285 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006286 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006287 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006288 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006289 }
arthurhungb89ccb02020-12-30 16:19:01 +08006290
6291 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006292 mDragWindow =
6293 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006294 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006295 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006296 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006297
6298 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006299 bool transferred =
6300 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6301 true /* isDragDrop */);
6302 if (transferred) {
6303 mWindow->consumeMotionCancel();
6304 mDragWindow->consumeMotionDown();
6305 }
6306 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006307 }
6308};
6309
6310TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006311 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006312
6313 // Move on window.
6314 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6315 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6316 ADISPLAY_ID_DEFAULT, {50, 50}))
6317 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6318 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6319 mWindow->consumeDragEvent(false, 50, 50);
6320 mSecondWindow->assertNoEvents();
6321
6322 // Move to another window.
6323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6324 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6325 ADISPLAY_ID_DEFAULT, {150, 50}))
6326 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6327 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6328 mWindow->consumeDragEvent(true, 150, 50);
6329 mSecondWindow->consumeDragEvent(false, 50, 50);
6330
6331 // Move back to original window.
6332 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6333 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6334 ADISPLAY_ID_DEFAULT, {50, 50}))
6335 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6336 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6337 mWindow->consumeDragEvent(false, 50, 50);
6338 mSecondWindow->consumeDragEvent(true, -50, 50);
6339
6340 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6341 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6342 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6343 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6344 mWindow->assertNoEvents();
6345 mSecondWindow->assertNoEvents();
6346}
6347
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006348TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006349 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006350
6351 // No cancel event after drag start
6352 mSpyWindow->assertNoEvents();
6353
6354 const MotionEvent secondFingerDownEvent =
6355 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6356 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6357 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6358 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6359 .build();
6360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6361 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6362 InputEventInjectionSync::WAIT_FOR_RESULT))
6363 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6364
6365 // Receives cancel for first pointer after next pointer down
6366 mSpyWindow->consumeMotionCancel();
6367 mSpyWindow->consumeMotionDown();
6368
6369 mSpyWindow->assertNoEvents();
6370}
6371
arthurhungf452d0b2021-01-06 00:19:52 +08006372TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006373 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006374
6375 // Move on window.
6376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6377 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6378 ADISPLAY_ID_DEFAULT, {50, 50}))
6379 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6380 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6381 mWindow->consumeDragEvent(false, 50, 50);
6382 mSecondWindow->assertNoEvents();
6383
6384 // Move to another window.
6385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6386 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6387 ADISPLAY_ID_DEFAULT, {150, 50}))
6388 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6389 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6390 mWindow->consumeDragEvent(true, 150, 50);
6391 mSecondWindow->consumeDragEvent(false, 50, 50);
6392
6393 // drop to another window.
6394 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6395 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6396 {150, 50}))
6397 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6398 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6399 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6400 mWindow->assertNoEvents();
6401 mSecondWindow->assertNoEvents();
6402}
6403
arthurhung6d4bed92021-03-17 11:59:33 +08006404TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006405 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006406
6407 // Move on window and keep button pressed.
6408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6409 injectMotionEvent(mDispatcher,
6410 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6411 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6412 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6413 .x(50)
6414 .y(50))
6415 .build()))
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 and release button, expect to drop item.
6422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6423 injectMotionEvent(mDispatcher,
6424 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6425 .buttonState(0)
6426 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6427 .x(150)
6428 .y(50))
6429 .build()))
6430 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6431 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6432 mWindow->assertNoEvents();
6433 mSecondWindow->assertNoEvents();
6434 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6435
6436 // nothing to the window.
6437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6438 injectMotionEvent(mDispatcher,
6439 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6440 .buttonState(0)
6441 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6442 .x(150)
6443 .y(50))
6444 .build()))
6445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6446 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6447 mWindow->assertNoEvents();
6448 mSecondWindow->assertNoEvents();
6449}
6450
Arthur Hung54745652022-04-20 07:17:41 +00006451TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006452 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006453
6454 // Set second window invisible.
6455 mSecondWindow->setVisible(false);
6456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6457
6458 // Move on window.
6459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6460 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6461 ADISPLAY_ID_DEFAULT, {50, 50}))
6462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6463 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6464 mWindow->consumeDragEvent(false, 50, 50);
6465 mSecondWindow->assertNoEvents();
6466
6467 // Move to another window.
6468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6469 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6470 ADISPLAY_ID_DEFAULT, {150, 50}))
6471 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6472 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6473 mWindow->consumeDragEvent(true, 150, 50);
6474 mSecondWindow->assertNoEvents();
6475
6476 // drop to another window.
6477 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6478 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6479 {150, 50}))
6480 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6481 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6482 mFakePolicy->assertDropTargetEquals(nullptr);
6483 mWindow->assertNoEvents();
6484 mSecondWindow->assertNoEvents();
6485}
6486
Arthur Hung54745652022-04-20 07:17:41 +00006487TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006488 // Ensure window could track pointerIds if it didn't support split touch.
6489 mWindow->setPreventSplitting(true);
6490
Arthur Hung54745652022-04-20 07:17:41 +00006491 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6492 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6493 {50, 50}))
6494 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6495 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6496
6497 const MotionEvent secondFingerDownEvent =
6498 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6499 .displayId(ADISPLAY_ID_DEFAULT)
6500 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6501 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6502 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6503 .build();
6504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6505 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6506 InputEventInjectionSync::WAIT_FOR_RESULT))
6507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6508 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6509
6510 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006511 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006512}
6513
6514TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6515 // First down on second window.
6516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6517 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6518 {150, 50}))
6519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6520
6521 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6522
6523 // Second down on first window.
6524 const MotionEvent secondFingerDownEvent =
6525 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6526 .displayId(ADISPLAY_ID_DEFAULT)
6527 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6528 .pointer(
6529 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6530 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6531 .build();
6532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6533 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6534 InputEventInjectionSync::WAIT_FOR_RESULT))
6535 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6536 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6537
6538 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006539 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006540
6541 // Move on window.
6542 const MotionEvent secondFingerMoveEvent =
6543 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6544 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6545 .pointer(
6546 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6547 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6548 .build();
6549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6550 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6551 InputEventInjectionSync::WAIT_FOR_RESULT));
6552 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6553 mWindow->consumeDragEvent(false, 50, 50);
6554 mSecondWindow->consumeMotionMove();
6555
6556 // Release the drag pointer should perform drop.
6557 const MotionEvent secondFingerUpEvent =
6558 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6559 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6560 .pointer(
6561 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6562 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6563 .build();
6564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6565 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6566 InputEventInjectionSync::WAIT_FOR_RESULT));
6567 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6568 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6569 mWindow->assertNoEvents();
6570 mSecondWindow->consumeMotionMove();
6571}
6572
Arthur Hung3915c1f2022-05-31 07:17:17 +00006573TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006574 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006575
6576 // Update window of second display.
6577 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006578 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006579 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6580
6581 // Let second display has a touch state.
6582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6583 injectMotionEvent(mDispatcher,
6584 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6585 AINPUT_SOURCE_TOUCHSCREEN)
6586 .displayId(SECOND_DISPLAY_ID)
6587 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6588 .x(100)
6589 .y(100))
6590 .build()));
6591 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6592 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6593 // Update window again.
6594 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6595
6596 // Move on window.
6597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6598 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6599 ADISPLAY_ID_DEFAULT, {50, 50}))
6600 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6601 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6602 mWindow->consumeDragEvent(false, 50, 50);
6603 mSecondWindow->assertNoEvents();
6604
6605 // Move to another window.
6606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6607 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6608 ADISPLAY_ID_DEFAULT, {150, 50}))
6609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6610 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6611 mWindow->consumeDragEvent(true, 150, 50);
6612 mSecondWindow->consumeDragEvent(false, 50, 50);
6613
6614 // drop to another window.
6615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6616 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6617 {150, 50}))
6618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6619 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6620 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6621 mWindow->assertNoEvents();
6622 mSecondWindow->assertNoEvents();
6623}
6624
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006625TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6626 startDrag(true, AINPUT_SOURCE_MOUSE);
6627 // Move on window.
6628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6629 injectMotionEvent(mDispatcher,
6630 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6631 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6632 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6633 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6634 .x(50)
6635 .y(50))
6636 .build()))
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,
6645 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6646 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6647 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6648 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6649 .x(150)
6650 .y(50))
6651 .build()))
6652 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6653 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6654 mWindow->consumeDragEvent(true, 150, 50);
6655 mSecondWindow->consumeDragEvent(false, 50, 50);
6656
6657 // drop to another window.
6658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6659 injectMotionEvent(mDispatcher,
6660 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6661 .buttonState(0)
6662 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6663 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6664 .x(150)
6665 .y(50))
6666 .build()))
6667 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6668 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6669 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6670 mWindow->assertNoEvents();
6671 mSecondWindow->assertNoEvents();
6672}
6673
Vishnu Nair062a8672021-09-03 16:07:44 -07006674class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6675
6676TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6677 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006678 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6679 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006680 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006681 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6682 window->setFocusable(true);
6683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6684 setFocusedWindow(window);
6685 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6686
6687 // With the flag set, window should not get any input
6688 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6689 mDispatcher->notifyKey(&keyArgs);
6690 window->assertNoEvents();
6691
6692 NotifyMotionArgs motionArgs =
6693 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6694 ADISPLAY_ID_DEFAULT);
6695 mDispatcher->notifyMotion(&motionArgs);
6696 window->assertNoEvents();
6697
6698 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006699 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6701
6702 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6703 mDispatcher->notifyKey(&keyArgs);
6704 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6705
6706 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6707 ADISPLAY_ID_DEFAULT);
6708 mDispatcher->notifyMotion(&motionArgs);
6709 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6710 window->assertNoEvents();
6711}
6712
6713TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6714 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6715 std::make_shared<FakeApplicationHandle>();
6716 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006717 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6718 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006719 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6720 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006721 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006722 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006723 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6724 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006725 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006726 window->setOwnerInfo(222, 222);
6727 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6728 window->setFocusable(true);
6729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6730 setFocusedWindow(window);
6731 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6732
6733 // With the flag set, window should not get any input
6734 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6735 mDispatcher->notifyKey(&keyArgs);
6736 window->assertNoEvents();
6737
6738 NotifyMotionArgs motionArgs =
6739 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6740 ADISPLAY_ID_DEFAULT);
6741 mDispatcher->notifyMotion(&motionArgs);
6742 window->assertNoEvents();
6743
6744 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006745 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6747
6748 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6749 mDispatcher->notifyKey(&keyArgs);
6750 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6751
6752 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6753 ADISPLAY_ID_DEFAULT);
6754 mDispatcher->notifyMotion(&motionArgs);
6755 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6756 window->assertNoEvents();
6757}
6758
6759TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6760 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6761 std::make_shared<FakeApplicationHandle>();
6762 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006763 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6764 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006765 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6766 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006767 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006768 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006769 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6770 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006771 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006772 window->setOwnerInfo(222, 222);
6773 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6774 window->setFocusable(true);
6775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6776 setFocusedWindow(window);
6777 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6778
6779 // With the flag set, window should not get any input
6780 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6781 mDispatcher->notifyKey(&keyArgs);
6782 window->assertNoEvents();
6783
6784 NotifyMotionArgs motionArgs =
6785 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6786 ADISPLAY_ID_DEFAULT);
6787 mDispatcher->notifyMotion(&motionArgs);
6788 window->assertNoEvents();
6789
6790 // When the window is no longer obscured because it went on top, it should get input
6791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6792
6793 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6794 mDispatcher->notifyKey(&keyArgs);
6795 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6796
6797 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6798 ADISPLAY_ID_DEFAULT);
6799 mDispatcher->notifyMotion(&motionArgs);
6800 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6801 window->assertNoEvents();
6802}
6803
Antonio Kantekf16f2832021-09-28 04:39:20 +00006804class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6805protected:
6806 std::shared_ptr<FakeApplicationHandle> mApp;
Antonio Kantek15beb512022-06-13 22:35:41 +00006807 std::shared_ptr<FakeApplicationHandle> mSecondaryApp;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006808 sp<FakeWindowHandle> mWindow;
6809 sp<FakeWindowHandle> mSecondWindow;
Antonio Kantek15beb512022-06-13 22:35:41 +00006810 sp<FakeWindowHandle> mThirdWindow;
Antonio Kantekf16f2832021-09-28 04:39:20 +00006811
6812 void SetUp() override {
6813 InputDispatcherTest::SetUp();
6814
6815 mApp = std::make_shared<FakeApplicationHandle>();
Antonio Kantek15beb512022-06-13 22:35:41 +00006816 mSecondaryApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006817 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006818 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006819 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006820 mSecondWindow =
6821 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006822 mSecondWindow->setFocusable(true);
Antonio Kantek15beb512022-06-13 22:35:41 +00006823 mThirdWindow =
6824 sp<FakeWindowHandle>::make(mSecondaryApp, mDispatcher,
6825 "TestWindow3_SecondaryDisplay", SECOND_DISPLAY_ID);
6826 mThirdWindow->setFocusable(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006827
6828 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Antonio Kantek15beb512022-06-13 22:35:41 +00006829 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}},
6830 {SECOND_DISPLAY_ID, {mThirdWindow}}});
6831 mThirdWindow->setOwnerInfo(SECONDARY_WINDOW_PID, SECONDARY_WINDOW_UID);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006832 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006833
Antonio Kantek15beb512022-06-13 22:35:41 +00006834 // Set main display initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006835 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kantek15beb512022-06-13 22:35:41 +00006836 WINDOW_UID, true /* hasPermission */,
6837 ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006838 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6839 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006840 mThirdWindow->assertNoEvents();
6841 }
6842
6843 // Set secondary display initial touch mode to InputDispatcher::kDefaultInTouchMode.
6844 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, SECONDARY_WINDOW_PID,
6845 SECONDARY_WINDOW_UID, true /* hasPermission */,
6846 SECOND_DISPLAY_ID)) {
6847 mWindow->assertNoEvents();
6848 mSecondWindow->assertNoEvents();
6849 mThirdWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
Antonio Kantek48710e42022-03-24 14:19:30 -07006850 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006851 }
6852
Antonio Kantek15beb512022-06-13 22:35:41 +00006853 void changeAndVerifyTouchModeInMainDisplayOnly(bool inTouchMode, int32_t pid, int32_t uid,
6854 bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006855 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6856 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006857 mWindow->consumeTouchModeEvent(inTouchMode);
6858 mSecondWindow->consumeTouchModeEvent(inTouchMode);
Antonio Kantek15beb512022-06-13 22:35:41 +00006859 mThirdWindow->assertNoEvents();
Antonio Kantekf16f2832021-09-28 04:39:20 +00006860 }
6861};
6862
Antonio Kantek26defcf2022-02-08 01:12:27 +00006863TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006864 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek15beb512022-06-13 22:35:41 +00006865 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode,
6866 windowInfo.ownerPid, windowInfo.ownerUid,
6867 false /* hasPermission */);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006868}
6869
Antonio Kantek26defcf2022-02-08 01:12:27 +00006870TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6871 const WindowInfo& windowInfo = *mWindow->getInfo();
6872 int32_t ownerPid = windowInfo.ownerPid;
6873 int32_t ownerUid = windowInfo.ownerUid;
6874 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6875 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006876 ownerUid, false /*hasPermission*/,
6877 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006878 mWindow->assertNoEvents();
6879 mSecondWindow->assertNoEvents();
6880}
6881
6882TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6883 const WindowInfo& windowInfo = *mWindow->getInfo();
6884 int32_t ownerPid = windowInfo.ownerPid;
6885 int32_t ownerUid = windowInfo.ownerUid;
6886 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
Antonio Kantek15beb512022-06-13 22:35:41 +00006887 changeAndVerifyTouchModeInMainDisplayOnly(!InputDispatcher::kDefaultInTouchMode, ownerPid,
6888 ownerUid, true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006889}
6890
Antonio Kantekf16f2832021-09-28 04:39:20 +00006891TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006892 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006893 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6894 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006895 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006896 mWindow->assertNoEvents();
6897 mSecondWindow->assertNoEvents();
6898}
6899
Antonio Kantek15beb512022-06-13 22:35:41 +00006900TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchOnSecondaryDisplayOnly) {
6901 const WindowInfo& windowInfo = *mThirdWindow->getInfo();
6902 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6903 windowInfo.ownerPid, windowInfo.ownerUid,
6904 true /*hasPermission*/, SECOND_DISPLAY_ID));
6905 mWindow->assertNoEvents();
6906 mSecondWindow->assertNoEvents();
6907 mThirdWindow->consumeTouchModeEvent(!InputDispatcher::kDefaultInTouchMode);
6908}
6909
Antonio Kantek48710e42022-03-24 14:19:30 -07006910TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6911 // Interact with the window first.
6912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6913 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6914 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6915
6916 // Then remove focus.
6917 mWindow->setFocusable(false);
6918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6919
6920 // Assert that caller can switch touch mode by owning one of the last interacted window.
6921 const WindowInfo& windowInfo = *mWindow->getInfo();
6922 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6923 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006924 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006925}
6926
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006927class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6928public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006929 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006930 std::shared_ptr<FakeApplicationHandle> application =
6931 std::make_shared<FakeApplicationHandle>();
6932 std::string name = "Fake Spy ";
6933 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006934 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
6935 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006936 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006937 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006938 return spy;
6939 }
6940
6941 sp<FakeWindowHandle> createForeground() {
6942 std::shared_ptr<FakeApplicationHandle> application =
6943 std::make_shared<FakeApplicationHandle>();
6944 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006945 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
6946 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006947 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006948 return window;
6949 }
6950
6951private:
6952 int mSpyCount{0};
6953};
6954
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006955using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006956/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006957 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6958 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006959TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6960 ScopedSilentDeath _silentDeath;
6961
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006962 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006963 spy->setTrustedOverlay(false);
6964 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6965 ".* not a trusted overlay");
6966}
6967
6968/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006969 * Input injection into a display with a spy window but no foreground windows should succeed.
6970 */
6971TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006972 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6974
6975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6976 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6978 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6979}
6980
6981/**
6982 * Verify the order in which different input windows receive events. The touched foreground window
6983 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6984 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6985 * receive events before ones belows it.
6986 *
6987 * Here, we set up a scenario with four windows in the following Z order from the top:
6988 * spy1, spy2, window, spy3.
6989 * We then inject an event and verify that the foreground "window" receives it first, followed by
6990 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6991 * window.
6992 */
6993TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6994 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006995 auto spy1 = createSpy();
6996 auto spy2 = createSpy();
6997 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6999 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
7000 const size_t numChannels = channels.size();
7001
Michael Wright8e9a8562022-02-09 13:44:29 +00007002 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007003 if (!epollFd.ok()) {
7004 FAIL() << "Failed to create epoll fd";
7005 }
7006
7007 for (size_t i = 0; i < numChannels; i++) {
7008 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
7009 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
7010 FAIL() << "Failed to add fd to epoll";
7011 }
7012 }
7013
7014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7017
7018 std::vector<size_t> eventOrder;
7019 std::vector<struct epoll_event> events(numChannels);
7020 for (;;) {
7021 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
7022 (100ms).count());
7023 if (nFds < 0) {
7024 FAIL() << "Failed to call epoll_wait";
7025 }
7026 if (nFds == 0) {
7027 break; // epoll_wait timed out
7028 }
7029 for (int i = 0; i < nFds; i++) {
Colin Cross5b799302022-10-18 21:52:41 -07007030 ASSERT_EQ(static_cast<uint32_t>(EPOLLIN), events[i].events);
Siarhei Vishniakou31977182022-09-30 08:51:23 -07007031 eventOrder.push_back(static_cast<size_t>(events[i].data.u64));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007032 channels[i]->consumeMotionDown();
7033 }
7034 }
7035
7036 // Verify the order in which the events were received.
7037 EXPECT_EQ(3u, eventOrder.size());
7038 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7039 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7040 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7041}
7042
7043/**
7044 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7045 */
7046TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7047 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007048 auto spy = createSpy();
7049 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7051
7052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7053 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7054 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7055 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7056 spy->assertNoEvents();
7057}
7058
7059/**
7060 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7061 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7062 * to the window.
7063 */
7064TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7065 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007066 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007067 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7069
7070 // Inject an event outside the spy window's touchable region.
7071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7072 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7073 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7074 window->consumeMotionDown();
7075 spy->assertNoEvents();
7076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7077 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7079 window->consumeMotionUp();
7080 spy->assertNoEvents();
7081
7082 // Inject an event inside the spy window's touchable region.
7083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7084 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7085 {5, 10}))
7086 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7087 window->consumeMotionDown();
7088 spy->consumeMotionDown();
7089}
7090
7091/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007092 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007093 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007094 */
7095TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7096 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007097 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007098 auto spy = createSpy();
7099 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007100 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007101 spy->setFrame(Rect{0, 0, 20, 20});
7102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7103
7104 // Inject an event outside the spy window's frame and touchable region.
7105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007106 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7107 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007108 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7109 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007110 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007111}
7112
7113/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007114 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7115 * pointers that are down within its bounds.
7116 */
7117TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7118 auto windowLeft = createForeground();
7119 windowLeft->setFrame({0, 0, 100, 200});
7120 auto windowRight = createForeground();
7121 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007122 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007123 spy->setFrame({0, 0, 200, 200});
7124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7125
7126 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7127 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7128 {50, 50}))
7129 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7130 windowLeft->consumeMotionDown();
7131 spy->consumeMotionDown();
7132
7133 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007134 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007135 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7136 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7137 .pointer(
7138 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7139 .build();
7140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7141 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7142 InputEventInjectionSync::WAIT_FOR_RESULT))
7143 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7144 windowRight->consumeMotionDown();
7145 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7146}
7147
7148/**
7149 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7150 * the spy should receive the second pointer with ACTION_DOWN.
7151 */
7152TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7153 auto window = createForeground();
7154 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007155 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007156 spyRight->setFrame({100, 0, 200, 200});
7157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7158
7159 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7160 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7161 {50, 50}))
7162 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7163 window->consumeMotionDown();
7164 spyRight->assertNoEvents();
7165
7166 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007167 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007168 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7169 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7170 .pointer(
7171 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7172 .build();
7173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7174 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7175 InputEventInjectionSync::WAIT_FOR_RESULT))
7176 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7177 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7178 spyRight->consumeMotionDown();
7179}
7180
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007181/**
7182 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7183 * windows should be allowed to control split touch.
7184 */
7185TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007186 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007187 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007188 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007189 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007190
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007191 auto window = createForeground();
7192 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007193
7194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7195
7196 // First finger down, no window touched.
7197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7198 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7199 {100, 200}))
7200 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7201 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7202 window->assertNoEvents();
7203
7204 // Second finger down on window, the window should receive touch down.
7205 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007206 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007207 .displayId(ADISPLAY_ID_DEFAULT)
7208 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7209 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7210 .x(100)
7211 .y(200))
7212 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7213 .build();
7214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7215 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7216 InputEventInjectionSync::WAIT_FOR_RESULT))
7217 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7218
7219 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7220 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7221}
7222
7223/**
7224 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7225 * do not receive key events.
7226 */
7227TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007228 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007229 spy->setFocusable(false);
7230
7231 auto window = createForeground();
7232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7233 setFocusedWindow(window);
7234 window->consumeFocusEvent(true);
7235
7236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7237 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7238 window->consumeKeyDown(ADISPLAY_ID_NONE);
7239
7240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7241 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7242 window->consumeKeyUp(ADISPLAY_ID_NONE);
7243
7244 spy->assertNoEvents();
7245}
7246
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007247using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7248
7249/**
7250 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7251 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7252 */
7253TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7254 auto window = createForeground();
7255 auto spy1 = createSpy();
7256 auto spy2 = createSpy();
7257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7258
7259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7260 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7261 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7262 window->consumeMotionDown();
7263 spy1->consumeMotionDown();
7264 spy2->consumeMotionDown();
7265
7266 // Pilfer pointers from the second spy window.
7267 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7268 spy2->assertNoEvents();
7269 spy1->consumeMotionCancel();
7270 window->consumeMotionCancel();
7271
7272 // The rest of the gesture should only be sent to the second spy window.
7273 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7274 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7275 ADISPLAY_ID_DEFAULT))
7276 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7277 spy2->consumeMotionMove();
7278 spy1->assertNoEvents();
7279 window->assertNoEvents();
7280}
7281
7282/**
7283 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7284 * in the middle of the gesture.
7285 */
7286TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7287 auto window = createForeground();
7288 auto spy = createSpy();
7289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7290
7291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7292 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7293 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7294 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7295 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7296
7297 window->releaseChannel();
7298
7299 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7300
7301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7302 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7303 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7304 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7305}
7306
7307/**
7308 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7309 * the spy, but not to any other windows.
7310 */
7311TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7312 auto spy = createSpy();
7313 auto window = createForeground();
7314
7315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7316
7317 // First finger down on the window and the spy.
7318 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7319 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7320 {100, 200}))
7321 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7322 spy->consumeMotionDown();
7323 window->consumeMotionDown();
7324
7325 // Spy window pilfers the pointers.
7326 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7327 window->consumeMotionCancel();
7328
7329 // Second finger down on the window and spy, but the window should not receive the pointer down.
7330 const MotionEvent secondFingerDownEvent =
7331 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7332 .displayId(ADISPLAY_ID_DEFAULT)
7333 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7334 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7335 .x(100)
7336 .y(200))
7337 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7338 .build();
7339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7340 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7341 InputEventInjectionSync::WAIT_FOR_RESULT))
7342 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7343
7344 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7345
7346 // Third finger goes down outside all windows, so injection should fail.
7347 const MotionEvent thirdFingerDownEvent =
7348 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7349 .displayId(ADISPLAY_ID_DEFAULT)
7350 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7351 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7352 .x(100)
7353 .y(200))
7354 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7355 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7356 .build();
7357 ASSERT_EQ(InputEventInjectionResult::FAILED,
7358 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7359 InputEventInjectionSync::WAIT_FOR_RESULT))
7360 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7361
7362 spy->assertNoEvents();
7363 window->assertNoEvents();
7364}
7365
7366/**
7367 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7368 */
7369TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7370 auto spy = createSpy();
7371 spy->setFrame(Rect(0, 0, 100, 100));
7372 auto window = createForeground();
7373 window->setFrame(Rect(0, 0, 200, 200));
7374
7375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7376
7377 // First finger down on the window only
7378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7379 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7380 {150, 150}))
7381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7382 window->consumeMotionDown();
7383
7384 // Second finger down on the spy and window
7385 const MotionEvent secondFingerDownEvent =
7386 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7387 .displayId(ADISPLAY_ID_DEFAULT)
7388 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7389 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7390 .x(150)
7391 .y(150))
7392 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7393 .build();
7394 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7395 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7396 InputEventInjectionSync::WAIT_FOR_RESULT))
7397 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7398 spy->consumeMotionDown();
7399 window->consumeMotionPointerDown(1);
7400
7401 // Third finger down on the spy and window
7402 const MotionEvent thirdFingerDownEvent =
7403 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7404 .displayId(ADISPLAY_ID_DEFAULT)
7405 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7406 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7407 .x(150)
7408 .y(150))
7409 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7410 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7411 .build();
7412 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7413 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7414 InputEventInjectionSync::WAIT_FOR_RESULT))
7415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7416 spy->consumeMotionPointerDown(1);
7417 window->consumeMotionPointerDown(2);
7418
7419 // Spy window pilfers the pointers.
7420 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7421 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7422 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7423
7424 spy->assertNoEvents();
7425 window->assertNoEvents();
7426}
7427
7428/**
7429 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7430 * other windows should be canceled. If this results in the cancellation of all pointers for some
7431 * window, then that window should receive ACTION_CANCEL.
7432 */
7433TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7434 auto spy = createSpy();
7435 spy->setFrame(Rect(0, 0, 100, 100));
7436 auto window = createForeground();
7437 window->setFrame(Rect(0, 0, 200, 200));
7438
7439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7440
7441 // First finger down on both spy and window
7442 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7443 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7444 {10, 10}))
7445 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7446 window->consumeMotionDown();
7447 spy->consumeMotionDown();
7448
7449 // Second finger down on the spy and window
7450 const MotionEvent secondFingerDownEvent =
7451 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7452 .displayId(ADISPLAY_ID_DEFAULT)
7453 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7454 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7455 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7456 .build();
7457 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7458 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7459 InputEventInjectionSync::WAIT_FOR_RESULT))
7460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7461 spy->consumeMotionPointerDown(1);
7462 window->consumeMotionPointerDown(1);
7463
7464 // Spy window pilfers the pointers.
7465 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7466 window->consumeMotionCancel();
7467
7468 spy->assertNoEvents();
7469 window->assertNoEvents();
7470}
7471
7472/**
7473 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7474 * be sent to other windows
7475 */
7476TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7477 auto spy = createSpy();
7478 spy->setFrame(Rect(0, 0, 100, 100));
7479 auto window = createForeground();
7480 window->setFrame(Rect(0, 0, 200, 200));
7481
7482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7483
7484 // First finger down on both window and spy
7485 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7486 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7487 {10, 10}))
7488 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7489 window->consumeMotionDown();
7490 spy->consumeMotionDown();
7491
7492 // Spy window pilfers the pointers.
7493 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7494 window->consumeMotionCancel();
7495
7496 // Second finger down on the window only
7497 const MotionEvent secondFingerDownEvent =
7498 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7499 .displayId(ADISPLAY_ID_DEFAULT)
7500 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7501 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7502 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7503 .x(150)
7504 .y(150))
7505 .build();
7506 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7507 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7508 InputEventInjectionSync::WAIT_FOR_RESULT))
7509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7510 window->consumeMotionDown();
7511 window->assertNoEvents();
7512
7513 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7514 spy->consumeMotionMove();
7515 spy->assertNoEvents();
7516}
7517
Prabir Pradhand65552b2021-10-07 11:23:50 -07007518class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7519public:
7520 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7521 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7522 std::make_shared<FakeApplicationHandle>();
7523 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007524 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7525 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007526 overlay->setFocusable(false);
7527 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007528 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007529 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007530 overlay->setTrustedOverlay(true);
7531
7532 std::shared_ptr<FakeApplicationHandle> application =
7533 std::make_shared<FakeApplicationHandle>();
7534 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007535 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7536 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007537 window->setFocusable(true);
7538 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007539
7540 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7542 setFocusedWindow(window);
7543 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7544 return {std::move(overlay), std::move(window)};
7545 }
7546
7547 void sendFingerEvent(int32_t action) {
7548 NotifyMotionArgs motionArgs =
7549 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7550 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7551 mDispatcher->notifyMotion(&motionArgs);
7552 }
7553
7554 void sendStylusEvent(int32_t action) {
7555 NotifyMotionArgs motionArgs =
7556 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7557 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7558 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7559 mDispatcher->notifyMotion(&motionArgs);
7560 }
7561};
7562
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007563using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7564
7565TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7566 ScopedSilentDeath _silentDeath;
7567
Prabir Pradhand65552b2021-10-07 11:23:50 -07007568 auto [overlay, window] = setupStylusOverlayScenario();
7569 overlay->setTrustedOverlay(false);
7570 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7571 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7572 ".* not a trusted overlay");
7573}
7574
7575TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7576 auto [overlay, window] = setupStylusOverlayScenario();
7577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7578
7579 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7580 overlay->consumeMotionDown();
7581 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7582 overlay->consumeMotionUp();
7583
7584 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7585 window->consumeMotionDown();
7586 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7587 window->consumeMotionUp();
7588
7589 overlay->assertNoEvents();
7590 window->assertNoEvents();
7591}
7592
7593TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7594 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007595 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7597
7598 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7599 overlay->consumeMotionDown();
7600 window->consumeMotionDown();
7601 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7602 overlay->consumeMotionUp();
7603 window->consumeMotionUp();
7604
7605 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7606 window->consumeMotionDown();
7607 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7608 window->consumeMotionUp();
7609
7610 overlay->assertNoEvents();
7611 window->assertNoEvents();
7612}
7613
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007614/**
7615 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7616 * The scenario is as follows:
7617 * - The stylus interceptor overlay is configured as a spy window.
7618 * - The stylus interceptor spy receives the start of a new stylus gesture.
7619 * - It pilfers pointers and then configures itself to no longer be a spy.
7620 * - The stylus interceptor continues to receive the rest of the gesture.
7621 */
7622TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7623 auto [overlay, window] = setupStylusOverlayScenario();
7624 overlay->setSpy(true);
7625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7626
7627 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7628 overlay->consumeMotionDown();
7629 window->consumeMotionDown();
7630
7631 // The interceptor pilfers the pointers.
7632 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7633 window->consumeMotionCancel();
7634
7635 // The interceptor configures itself so that it is no longer a spy.
7636 overlay->setSpy(false);
7637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7638
7639 // It continues to receive the rest of the stylus gesture.
7640 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7641 overlay->consumeMotionMove();
7642 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7643 overlay->consumeMotionUp();
7644
7645 window->assertNoEvents();
7646}
7647
Prabir Pradhan5735a322022-04-11 17:23:34 +00007648struct User {
7649 int32_t mPid;
7650 int32_t mUid;
7651 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7652 std::unique_ptr<InputDispatcher>& mDispatcher;
7653
7654 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7655 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7656
7657 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7658 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7659 ADISPLAY_ID_DEFAULT, {100, 200},
7660 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7661 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7662 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7663 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7664 }
7665
7666 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7667 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7668 InputEventInjectionSync::WAIT_FOR_RESULT,
7669 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7670 mPolicyFlags);
7671 }
7672
7673 sp<FakeWindowHandle> createWindow() const {
7674 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7675 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007676 sp<FakeWindowHandle> window =
7677 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7678 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007679 window->setOwnerInfo(mPid, mUid);
7680 return window;
7681 }
7682};
7683
7684using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7685
7686TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7687 auto owner = User(mDispatcher, 10, 11);
7688 auto window = owner.createWindow();
7689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7690
7691 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7692 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7693 window->consumeMotionDown();
7694
7695 setFocusedWindow(window);
7696 window->consumeFocusEvent(true);
7697
7698 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7699 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7700 window->consumeKeyDown(ADISPLAY_ID_NONE);
7701}
7702
7703TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7704 auto owner = User(mDispatcher, 10, 11);
7705 auto window = owner.createWindow();
7706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7707
7708 auto rando = User(mDispatcher, 20, 21);
7709 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7710 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7711
7712 setFocusedWindow(window);
7713 window->consumeFocusEvent(true);
7714
7715 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7716 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7717 window->assertNoEvents();
7718}
7719
7720TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7721 auto owner = User(mDispatcher, 10, 11);
7722 auto window = owner.createWindow();
7723 auto spy = owner.createWindow();
7724 spy->setSpy(true);
7725 spy->setTrustedOverlay(true);
7726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7727
7728 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7729 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7730 spy->consumeMotionDown();
7731 window->consumeMotionDown();
7732}
7733
7734TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7735 auto owner = User(mDispatcher, 10, 11);
7736 auto window = owner.createWindow();
7737
7738 auto rando = User(mDispatcher, 20, 21);
7739 auto randosSpy = rando.createWindow();
7740 randosSpy->setSpy(true);
7741 randosSpy->setTrustedOverlay(true);
7742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7743
7744 // The event is targeted at owner's window, so injection should succeed, but the spy should
7745 // not receive the event.
7746 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7747 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7748 randosSpy->assertNoEvents();
7749 window->consumeMotionDown();
7750}
7751
7752TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7753 auto owner = User(mDispatcher, 10, 11);
7754 auto window = owner.createWindow();
7755
7756 auto rando = User(mDispatcher, 20, 21);
7757 auto randosSpy = rando.createWindow();
7758 randosSpy->setSpy(true);
7759 randosSpy->setTrustedOverlay(true);
7760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7761
7762 // A user that has injection permission can inject into any window.
7763 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7764 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7765 ADISPLAY_ID_DEFAULT));
7766 randosSpy->consumeMotionDown();
7767 window->consumeMotionDown();
7768
7769 setFocusedWindow(randosSpy);
7770 randosSpy->consumeFocusEvent(true);
7771
7772 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7773 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7774 window->assertNoEvents();
7775}
7776
7777TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7778 auto owner = User(mDispatcher, 10, 11);
7779 auto window = owner.createWindow();
7780
7781 auto rando = User(mDispatcher, 20, 21);
7782 auto randosWindow = rando.createWindow();
7783 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7784 randosWindow->setWatchOutsideTouch(true);
7785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7786
7787 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7788 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7789 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7790 window->consumeMotionDown();
7791 randosWindow->consumeMotionOutside();
7792}
7793
Garfield Tane84e6f92019-08-29 17:28:41 -07007794} // namespace android::inputdispatcher