blob: 7ee6950b095723fc4cdcbbea78dcda91e3a81ae3 [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
Prabir Pradhan5735a322022-04-11 17:23:34 +000066// The default pid and uid for windows created by the test.
67static constexpr int32_t WINDOW_PID = 999;
68static constexpr int32_t WINDOW_UID = 1001;
69
70// The default policy flags to use for event injection by tests.
71static constexpr uint32_t DEFAULT_POLICY_FLAGS = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000073// An arbitrary pid of the gesture monitor window
74static constexpr int32_t MONITOR_PID = 2001;
75
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080076static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
77
chaviwd1c23182019-12-20 18:44:56 -080078struct PointF {
79 float x;
80 float y;
81};
Michael Wrightd02c5b62014-02-10 15:10:22 -080082
Gang Wang342c9272020-01-13 13:15:04 -050083/**
84 * Return a DOWN key event with KEYCODE_A.
85 */
86static KeyEvent getTestKeyEvent() {
87 KeyEvent event;
88
Garfield Tanfbe732e2020-01-24 11:26:14 -080089 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
90 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
91 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050092 return event;
93}
94
Siarhei Vishniakouca205502021-07-16 21:31:58 +000095static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
96 ASSERT_EQ(expectedAction, receivedAction)
97 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
98 << MotionEvent::actionToString(receivedAction);
99}
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101// --- FakeInputDispatcherPolicy ---
102
103class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
104 InputDispatcherConfiguration mConfig;
105
Prabir Pradhanedd96402022-02-15 01:46:16 -0800106 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
107
Michael Wrightd02c5b62014-02-10 15:10:22 -0800108protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000109 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800110
111public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000112 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800113
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800114 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700115 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
116 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
117 EXPECT_EQ(event.getDisplayId(), args.displayId);
118
119 const auto& keyEvent = static_cast<const KeyEvent&>(event);
120 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
121 EXPECT_EQ(keyEvent.getAction(), args.action);
122 });
Jackal Guof9696682018-10-05 12:23:23 +0800123 }
124
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700125 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
126 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
127 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
128 EXPECT_EQ(event.getDisplayId(), args.displayId);
129
130 const auto& motionEvent = static_cast<const MotionEvent&>(event);
131 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
132 EXPECT_EQ(motionEvent.getAction(), args.action);
133 EXPECT_EQ(motionEvent.getX(0), point.x);
134 EXPECT_EQ(motionEvent.getY(0), point.y);
135 EXPECT_EQ(motionEvent.getRawX(0), point.x);
136 EXPECT_EQ(motionEvent.getRawY(0), point.y);
137 });
Jackal Guof9696682018-10-05 12:23:23 +0800138 }
139
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700140 void assertFilterInputEventWasNotCalled() {
141 std::scoped_lock lock(mLock);
142 ASSERT_EQ(nullptr, mFilteredEvent);
143 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800145 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700146 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 ASSERT_TRUE(mConfigurationChangedTime)
148 << "Timed out waiting for configuration changed call";
149 ASSERT_EQ(*mConfigurationChangedTime, when);
150 mConfigurationChangedTime = std::nullopt;
151 }
152
153 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700154 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800155 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800156 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800157 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
158 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
159 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
160 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
161 mLastNotifySwitch = std::nullopt;
162 }
163
chaviwfd6d3512019-03-25 13:23:49 -0700164 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700165 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800166 ASSERT_EQ(touchedToken, mOnPointerDownToken);
167 mOnPointerDownToken.clear();
168 }
169
170 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700171 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800172 ASSERT_TRUE(mOnPointerDownToken == nullptr)
173 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700174 }
175
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700176 // This function must be called soon after the expected ANR timer starts,
177 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700179 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500180 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800181 std::unique_lock lock(mLock);
182 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500183 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800184 ASSERT_NO_FATAL_FAILURE(
185 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700187 }
188
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000189 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800190 const sp<WindowInfoHandle>& window) {
191 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
192 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
193 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500194 }
195
Prabir Pradhanedd96402022-02-15 01:46:16 -0800196 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
197 const sp<IBinder>& expectedToken,
198 int32_t expectedPid) {
199 std::unique_lock lock(mLock);
200 android::base::ScopedLockAssertion assumeLocked(mLock);
201 AnrResult result;
202 ASSERT_NO_FATAL_FAILURE(result =
203 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
204 const auto& [token, pid] = result;
205 ASSERT_EQ(expectedToken, token);
206 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500207 }
208
Prabir Pradhanedd96402022-02-15 01:46:16 -0800209 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000210 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500211 std::unique_lock lock(mLock);
212 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800213 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
214 const auto& [token, _] = result;
215 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000216 }
217
Prabir Pradhanedd96402022-02-15 01:46:16 -0800218 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
219 int32_t expectedPid) {
220 std::unique_lock lock(mLock);
221 android::base::ScopedLockAssertion assumeLocked(mLock);
222 AnrResult result;
223 ASSERT_NO_FATAL_FAILURE(
224 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
225 const auto& [token, pid] = result;
226 ASSERT_EQ(expectedToken, token);
227 ASSERT_EQ(expectedPid, pid);
228 }
229
230 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000231 sp<IBinder> getResponsiveWindowToken() {
232 std::unique_lock lock(mLock);
233 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800234 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
235 const auto& [token, _] = result;
236 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700237 }
238
239 void assertNotifyAnrWasNotCalled() {
240 std::scoped_lock lock(mLock);
241 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800242 ASSERT_TRUE(mAnrWindows.empty());
243 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500244 << "ANR was not called, but please also consume the 'connection is responsive' "
245 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700246 }
247
Garfield Tan1c7bc862020-01-28 13:24:04 -0800248 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
249 mConfig.keyRepeatTimeout = timeout;
250 mConfig.keyRepeatDelay = delay;
251 }
252
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000253 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800254 std::unique_lock lock(mLock);
255 base::ScopedLockAssertion assumeLocked(mLock);
256
257 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
258 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000259 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800260 enabled;
261 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000262 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
263 << ") to be called.";
264 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800265 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000266 auto request = *mPointerCaptureRequest;
267 mPointerCaptureRequest.reset();
268 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 }
270
271 void assertSetPointerCaptureNotCalled() {
272 std::unique_lock lock(mLock);
273 base::ScopedLockAssertion assumeLocked(mLock);
274
275 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000276 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800277 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000278 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800279 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000280 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800281 }
282
arthurhungf452d0b2021-01-06 00:19:52 +0800283 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
284 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800285 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800286 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800287 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800288 }
289
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800290 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
291 std::unique_lock lock(mLock);
292 base::ScopedLockAssertion assumeLocked(mLock);
293 std::optional<sp<IBinder>> receivedToken =
294 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
295 mNotifyInputChannelBroken);
296 ASSERT_TRUE(receivedToken.has_value());
297 ASSERT_EQ(token, *receivedToken);
298 }
299
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800300 /**
301 * Set policy timeout. A value of zero means next key will not be intercepted.
302 */
303 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
304 mInterceptKeyTimeout = timeout;
305 }
306
Michael Wrightd02c5b62014-02-10 15:10:22 -0800307private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700308 std::mutex mLock;
309 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
310 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
311 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
312 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800313
Prabir Pradhan99987712020-11-10 18:43:05 -0800314 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000315
316 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800317
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700318 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700319 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800320 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
321 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700322 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800323 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
324 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700325
arthurhungf452d0b2021-01-06 00:19:52 +0800326 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800327 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800328
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800329 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
330
Prabir Pradhanedd96402022-02-15 01:46:16 -0800331 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
332 // for a specific container to become non-empty. When the container is non-empty, return the
333 // first entry from the container and erase it.
334 template <class T>
335 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
336 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
337 // If there is an ANR, Dispatcher won't be idle because there are still events
338 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
339 // before checking if ANR was called.
340 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
341 // to provide it some time to act. 100ms seems reasonable.
342 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
343 const std::chrono::time_point start = std::chrono::steady_clock::now();
344 std::optional<T> token =
345 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
346 if (!token.has_value()) {
347 ADD_FAILURE() << "Did not receive the ANR callback";
348 return {};
349 }
350
351 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
352 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
353 // the dispatcher started counting before this function was called
354 if (std::chrono::abs(timeout - waited) > 100ms) {
355 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
356 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
357 << "ms, but waited "
358 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
359 << "ms instead";
360 }
361 return *token;
362 }
363
364 template <class T>
365 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
366 std::queue<T>& storage,
367 std::unique_lock<std::mutex>& lock,
368 std::condition_variable& condition)
369 REQUIRES(mLock) {
370 condition.wait_for(lock, timeout,
371 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
372 if (storage.empty()) {
373 ADD_FAILURE() << "Did not receive the expected callback";
374 return std::nullopt;
375 }
376 T item = storage.front();
377 storage.pop();
378 return std::make_optional(item);
379 }
380
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600381 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700382 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800383 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800384 }
385
Prabir Pradhanedd96402022-02-15 01:46:16 -0800386 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
387 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700388 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800389 ASSERT_TRUE(pid.has_value());
390 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700391 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500392 }
393
Prabir Pradhanedd96402022-02-15 01:46:16 -0800394 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
395 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500396 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800397 ASSERT_TRUE(pid.has_value());
398 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500399 mNotifyAnr.notify_all();
400 }
401
402 void notifyNoFocusedWindowAnr(
403 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
404 std::scoped_lock lock(mLock);
405 mAnrApplications.push(applicationHandle);
406 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 }
408
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800409 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
410 std::scoped_lock lock(mLock);
411 mBrokenInputChannels.push(connectionToken);
412 mNotifyInputChannelBroken.notify_all();
413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700416
Chris Yef59a2f42020-10-16 12:55:26 -0700417 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
418 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
419 const std::vector<float>& values) override {}
420
421 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
422 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000423
Chris Yefb552902021-02-03 17:18:37 -0800424 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
425
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600426 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 *outConfig = mConfig;
428 }
429
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600430 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700431 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800432 switch (inputEvent->getType()) {
433 case AINPUT_EVENT_TYPE_KEY: {
434 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800435 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800436 break;
437 }
438
439 case AINPUT_EVENT_TYPE_MOTION: {
440 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800441 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800442 break;
443 }
444 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800445 return true;
446 }
447
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800448 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
449 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
450 // Clear intercept state when we handled the event.
451 mInterceptKeyTimeout = 0ms;
452 }
453 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600455 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600457 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800458 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
459 // Clear intercept state so we could dispatch the event in next wake.
460 mInterceptKeyTimeout = 0ms;
461 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 }
463
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600464 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 return false;
466 }
467
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600468 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
469 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700470 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800471 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
472 * essentially a passthrough for notifySwitch.
473 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800474 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 }
476
Sean Stoutb4e0a592021-02-23 07:34:53 -0800477 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800478
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600479 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700480 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700481 mOnPointerDownToken = newToken;
482 }
483
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000484 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000486 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800487 mPointerCaptureChangedCondition.notify_all();
488 }
489
arthurhungf452d0b2021-01-06 00:19:52 +0800490 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
491 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800492 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800493 mDropTargetWindowToken = token;
494 }
495
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700496 void assertFilterInputEventWasCalledInternal(
497 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700498 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800499 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700500 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800501 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800502 }
Antonio Kanteka042c022022-07-06 16:51:07 -0700503
504 bool isPerDisplayTouchModeEnabled() {
505 // TODO(b/198499018): Make this a regular property once per display touch mode is enabled
506 return false;
507 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508};
509
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510// --- InputDispatcherTest ---
511
512class InputDispatcherTest : public testing::Test {
513protected:
514 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700515 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000517 void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700518 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800519 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800520 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000521 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700522 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800523 }
524
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000525 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700526 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800527 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700528 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800529 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700530
531 /**
532 * Used for debugging when writing the test
533 */
534 void dumpDispatcherState() {
535 std::string dump;
536 mDispatcher->dump(dump);
537 std::stringstream ss(dump);
538 std::string to;
539
540 while (std::getline(ss, to, '\n')) {
541 ALOGE("%s", to.c_str());
542 }
543 }
Vishnu Nair958da932020-08-21 17:12:37 -0700544
chaviw3277faf2021-05-19 16:45:23 -0500545 void setFocusedWindow(const sp<WindowInfoHandle>& window,
546 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700547 FocusRequest request;
548 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000549 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700550 if (focusedWindow) {
551 request.focusedToken = focusedWindow->getToken();
552 }
553 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
554 request.displayId = window->getInfo()->displayId;
555 mDispatcher->setFocusedWindow(request);
556 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800557};
558
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
560 KeyEvent event;
561
562 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800563 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
564 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600565 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
566 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800567 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000568 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
569 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800570 << "Should reject key events with undefined action.";
571
572 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800573 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
574 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600575 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800576 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000577 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
578 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 << "Should reject key events with ACTION_MULTIPLE.";
580}
581
582TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
583 MotionEvent event;
584 PointerProperties pointerProperties[MAX_POINTERS + 1];
585 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800586 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800587 pointerProperties[i].clear();
588 pointerProperties[i].id = i;
589 pointerCoords[i].clear();
590 }
591
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800592 // Some constants commonly used below
593 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
594 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
595 constexpr int32_t metaState = AMETA_NONE;
596 constexpr MotionClassification classification = MotionClassification::NONE;
597
chaviw9eaa22c2020-07-01 16:21:27 -0700598 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800600 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700601 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
602 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
604 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700605 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800606 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000607 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
608 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 << "Should reject motion events with undefined action.";
610
611 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800612 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800613 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
614 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
615 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
616 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500617 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800618 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000619 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
620 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 << "Should reject motion events with pointer down index too large.";
622
Garfield Tanfbe732e2020-01-24 11:26:14 -0800623 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700624 AMOTION_EVENT_ACTION_POINTER_DOWN |
625 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700626 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
627 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700628 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500629 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800630 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000631 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
632 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800633 << "Should reject motion events with pointer down index too small.";
634
635 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800636 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800637 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
638 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
639 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
640 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500641 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800642 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000643 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
644 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800645 << "Should reject motion events with pointer up index too large.";
646
Garfield Tanfbe732e2020-01-24 11:26:14 -0800647 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700648 AMOTION_EVENT_ACTION_POINTER_UP |
649 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700650 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
651 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700652 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500653 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800654 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000655 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
656 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 << "Should reject motion events with pointer up index too small.";
658
659 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800660 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
661 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700662 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700663 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
664 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700665 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800666 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000667 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
668 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800669 << "Should reject motion events with 0 pointers.";
670
Garfield Tanfbe732e2020-01-24 11:26:14 -0800671 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
672 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700673 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700674 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
675 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700676 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000678 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
679 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 << "Should reject motion events with more than MAX_POINTERS pointers.";
681
682 // Rejects motion events with invalid pointer ids.
683 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800684 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
685 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700686 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700687 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
688 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700689 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800690 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000691 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
692 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800693 << "Should reject motion events with pointer ids less than 0.";
694
695 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800696 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
697 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700698 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700699 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
700 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700701 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800702 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000703 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
704 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800705 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
706
707 // Rejects motion events with duplicate pointer ids.
708 pointerProperties[0].id = 1;
709 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800710 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
711 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700712 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700713 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
714 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700715 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800716 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan5735a322022-04-11 17:23:34 +0000717 mDispatcher->injectInputEvent(&event, {} /*targetUid*/, InputEventInjectionSync::NONE,
718 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719 << "Should reject motion events with duplicate pointer ids.";
720}
721
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800722/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
723
724TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
725 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800726 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800727 mDispatcher->notifyConfigurationChanged(&args);
728 ASSERT_TRUE(mDispatcher->waitForIdle());
729
730 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
731}
732
733TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800734 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
735 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800736 mDispatcher->notifySwitch(&args);
737
738 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
739 args.policyFlags |= POLICY_FLAG_TRUSTED;
740 mFakePolicy->assertNotifySwitchWasCalled(args);
741}
742
Arthur Hungb92218b2018-08-14 12:00:21 +0800743// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700744static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700745// Default input dispatching timeout if there is no focused application or paused window
746// from which to determine an appropriate dispatching timeout.
747static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
748 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
749 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800750
751class FakeApplicationHandle : public InputApplicationHandle {
752public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700753 FakeApplicationHandle() {
754 mInfo.name = "Fake Application";
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -0700755 mInfo.token = sp<BBinder>::make();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500756 mInfo.dispatchingTimeoutMillis =
757 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700758 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800759 virtual ~FakeApplicationHandle() {}
760
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000761 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700762
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500763 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
764 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700765 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800766};
767
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800768class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800769public:
Garfield Tan15601662020-09-22 15:32:38 -0700770 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800771 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700772 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800773 }
774
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800775 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700776 InputEvent* event;
777 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
778 if (!consumeSeq) {
779 return nullptr;
780 }
781 finishEvent(*consumeSeq);
782 return event;
783 }
784
785 /**
786 * Receive an event without acknowledging it.
787 * Return the sequence number that could later be used to send finished signal.
788 */
789 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800790 uint32_t consumeSeq;
791 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800792
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800793 std::chrono::time_point start = std::chrono::steady_clock::now();
794 status_t status = WOULD_BLOCK;
795 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800796 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800797 &event);
798 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
799 if (elapsed > 100ms) {
800 break;
801 }
802 }
803
804 if (status == WOULD_BLOCK) {
805 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700806 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800807 }
808
809 if (status != OK) {
810 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700811 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800812 }
813 if (event == nullptr) {
814 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700815 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700817 if (outEvent != nullptr) {
818 *outEvent = event;
819 }
820 return consumeSeq;
821 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800822
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700823 /**
824 * To be used together with "receiveEvent" to complete the consumption of an event.
825 */
826 void finishEvent(uint32_t consumeSeq) {
827 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
828 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800829 }
830
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000831 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
832 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
833 ASSERT_EQ(OK, status);
834 }
835
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000836 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
837 std::optional<int32_t> expectedDisplayId,
838 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800839 InputEvent* event = consume();
840
841 ASSERT_NE(nullptr, event) << mName.c_str()
842 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800843 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700844 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800845 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800846
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000847 if (expectedDisplayId.has_value()) {
848 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
849 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800850
Tiger Huang8664f8c2018-10-11 19:14:35 +0800851 switch (expectedEventType) {
852 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800853 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
854 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000855 if (expectedFlags.has_value()) {
856 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
857 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800858 break;
859 }
860 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800861 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000862 assertMotionAction(expectedAction, motionEvent.getAction());
863
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000864 if (expectedFlags.has_value()) {
865 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
866 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800867 break;
868 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100869 case AINPUT_EVENT_TYPE_FOCUS: {
870 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
871 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800872 case AINPUT_EVENT_TYPE_CAPTURE: {
873 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
874 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000875 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
876 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
877 }
arthurhungb89ccb02020-12-30 16:19:01 +0800878 case AINPUT_EVENT_TYPE_DRAG: {
879 FAIL() << "Use 'consumeDragEvent' for DRAG events";
880 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800881 default: {
882 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
883 }
884 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800885 }
886
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100887 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
888 InputEvent* event = consume();
889 ASSERT_NE(nullptr, event) << mName.c_str()
890 << ": consumer should have returned non-NULL event.";
891 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
892 << "Got " << inputEventTypeToString(event->getType())
893 << " event instead of FOCUS event";
894
895 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
896 << mName.c_str() << ": event displayId should always be NONE.";
897
898 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
899 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100900 }
901
Prabir Pradhan99987712020-11-10 18:43:05 -0800902 void consumeCaptureEvent(bool hasCapture) {
903 const InputEvent* event = consume();
904 ASSERT_NE(nullptr, event) << mName.c_str()
905 << ": consumer should have returned non-NULL event.";
906 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
907 << "Got " << inputEventTypeToString(event->getType())
908 << " event instead of CAPTURE event";
909
910 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
911 << mName.c_str() << ": event displayId should always be NONE.";
912
913 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
914 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
915 }
916
arthurhungb89ccb02020-12-30 16:19:01 +0800917 void consumeDragEvent(bool isExiting, float x, float y) {
918 const InputEvent* event = consume();
919 ASSERT_NE(nullptr, event) << mName.c_str()
920 << ": consumer should have returned non-NULL event.";
921 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
922 << "Got " << inputEventTypeToString(event->getType())
923 << " event instead of DRAG event";
924
925 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
926 << mName.c_str() << ": event displayId should always be NONE.";
927
928 const auto& dragEvent = static_cast<const DragEvent&>(*event);
929 EXPECT_EQ(isExiting, dragEvent.isExiting());
930 EXPECT_EQ(x, dragEvent.getX());
931 EXPECT_EQ(y, dragEvent.getY());
932 }
933
Antonio Kantekf16f2832021-09-28 04:39:20 +0000934 void consumeTouchModeEvent(bool inTouchMode) {
935 const InputEvent* event = consume();
936 ASSERT_NE(nullptr, event) << mName.c_str()
937 << ": consumer should have returned non-NULL event.";
938 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
939 << "Got " << inputEventTypeToString(event->getType())
940 << " event instead of TOUCH_MODE event";
941
942 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
943 << mName.c_str() << ": event displayId should always be NONE.";
944 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
945 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
946 }
947
chaviwd1c23182019-12-20 18:44:56 -0800948 void assertNoEvents() {
949 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 if (event == nullptr) {
951 return;
952 }
953 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
954 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
955 ADD_FAILURE() << "Received key event "
956 << KeyEvent::actionToString(keyEvent.getAction());
957 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
958 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
959 ADD_FAILURE() << "Received motion event "
960 << MotionEvent::actionToString(motionEvent.getAction());
961 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
962 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
963 ADD_FAILURE() << "Received focus event, hasFocus = "
964 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800965 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
966 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
967 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
968 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000969 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
970 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
971 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
972 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700973 }
974 FAIL() << mName.c_str()
975 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800976 }
977
978 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
979
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800980 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
981
chaviwd1c23182019-12-20 18:44:56 -0800982protected:
983 std::unique_ptr<InputConsumer> mConsumer;
984 PreallocatedInputEventFactory mEventFactory;
985
986 std::string mName;
987};
988
chaviw3277faf2021-05-19 16:45:23 -0500989class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800990public:
991 static const int32_t WIDTH = 600;
992 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800993
Chris Yea209fde2020-07-22 13:54:51 -0700994 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700995 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500996 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800997 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500998 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700999 base::Result<std::unique_ptr<InputChannel>> channel =
1000 dispatcher->createInputChannel(name);
1001 token = (*channel)->getConnectionToken();
1002 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -08001003 }
1004
1005 inputApplicationHandle->updateInfo();
1006 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1007
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001008 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001009 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001010 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001011 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001012 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001013 mInfo.frameLeft = 0;
1014 mInfo.frameTop = 0;
1015 mInfo.frameRight = WIDTH;
1016 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001017 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001018 mInfo.globalScaleFactor = 1.0;
1019 mInfo.touchableRegion.clear();
1020 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan5735a322022-04-11 17:23:34 +00001021 mInfo.ownerPid = WINDOW_PID;
1022 mInfo.ownerUid = WINDOW_UID;
chaviwd1c23182019-12-20 18:44:56 -08001023 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001024 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001025 }
1026
Arthur Hungabbb9d82021-09-01 14:52:30 +00001027 sp<FakeWindowHandle> clone(
1028 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001029 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001030 sp<FakeWindowHandle> handle =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001031 sp<FakeWindowHandle>::make(inputApplicationHandle, dispatcher,
1032 mInfo.name + "(Mirror)", displayId, mInfo.token);
Arthur Hungabbb9d82021-09-01 14:52:30 +00001033 return handle;
1034 }
1035
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001036 void setTouchable(bool touchable) {
1037 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1038 }
chaviwd1c23182019-12-20 18:44:56 -08001039
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001040 void setFocusable(bool focusable) {
1041 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1042 }
1043
1044 void setVisible(bool visible) {
1045 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1046 }
Vishnu Nair958da932020-08-21 17:12:37 -07001047
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001048 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001049 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001050 }
1051
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001052 void setPaused(bool paused) {
1053 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1054 }
1055
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001056 void setPreventSplitting(bool preventSplitting) {
1057 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001058 }
1059
1060 void setSlippery(bool slippery) {
1061 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1062 }
1063
1064 void setWatchOutsideTouch(bool watchOutside) {
1065 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1066 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001067
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001068 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1069
1070 void setInterceptsStylus(bool interceptsStylus) {
1071 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1072 }
1073
1074 void setDropInput(bool dropInput) {
1075 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1076 }
1077
1078 void setDropInputIfObscured(bool dropInputIfObscured) {
1079 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1080 }
1081
1082 void setNoInputChannel(bool noInputChannel) {
1083 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1084 }
1085
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001086 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1087
chaviw3277faf2021-05-19 16:45:23 -05001088 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001089
Bernardo Rufino7393d172021-02-26 13:56:11 +00001090 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1091
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001092 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001093 mInfo.frameLeft = frame.left;
1094 mInfo.frameTop = frame.top;
1095 mInfo.frameRight = frame.right;
1096 mInfo.frameBottom = frame.bottom;
1097 mInfo.touchableRegion.clear();
1098 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001099
1100 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1101 ui::Transform translate;
1102 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1103 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001104 }
1105
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001106 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1107
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001108 void setIsWallpaper(bool isWallpaper) {
1109 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1110 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001111
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001112 void setDupTouchToWallpaper(bool hasWallpaper) {
1113 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1114 }
chaviwd1c23182019-12-20 18:44:56 -08001115
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001116 void setTrustedOverlay(bool trustedOverlay) {
1117 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1118 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001119
chaviw9eaa22c2020-07-01 16:21:27 -07001120 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1121 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1122 }
1123
1124 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001125
yunho.shinf4a80b82020-11-16 21:13:57 +09001126 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1127
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001128 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1129 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1130 expectedFlags);
1131 }
1132
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001133 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1134 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1135 }
1136
Svet Ganov5d3bc372020-01-26 23:11:07 -08001137 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001138 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001139 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1140 expectedFlags);
1141 }
1142
1143 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001145 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1146 expectedFlags);
1147 }
1148
1149 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001150 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001151 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1152 }
1153
1154 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1155 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001156 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1157 expectedFlags);
1158 }
1159
Svet Ganov5d3bc372020-01-26 23:11:07 -08001160 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001161 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1162 int32_t expectedFlags = 0) {
1163 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1164 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001165 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1166 }
1167
1168 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001169 int32_t expectedFlags = 0) {
1170 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1171 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001172 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1173 }
1174
1175 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001176 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001177 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1178 expectedFlags);
1179 }
1180
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001181 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1182 int32_t expectedFlags = 0) {
1183 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1184 expectedFlags);
1185 }
1186
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001187 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1188 int32_t expectedFlags = 0) {
1189 InputEvent* event = consume();
1190 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1191 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1192 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1193 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1194 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1195 }
1196
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001197 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1198 ASSERT_NE(mInputReceiver, nullptr)
1199 << "Cannot consume events from a window with no receiver";
1200 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1201 }
1202
Prabir Pradhan99987712020-11-10 18:43:05 -08001203 void consumeCaptureEvent(bool hasCapture) {
1204 ASSERT_NE(mInputReceiver, nullptr)
1205 << "Cannot consume events from a window with no receiver";
1206 mInputReceiver->consumeCaptureEvent(hasCapture);
1207 }
1208
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001209 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1210 std::optional<int32_t> expectedDisplayId,
1211 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001212 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1213 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1214 expectedFlags);
1215 }
1216
arthurhungb89ccb02020-12-30 16:19:01 +08001217 void consumeDragEvent(bool isExiting, float x, float y) {
1218 mInputReceiver->consumeDragEvent(isExiting, x, y);
1219 }
1220
Antonio Kantekf16f2832021-09-28 04:39:20 +00001221 void consumeTouchModeEvent(bool inTouchMode) {
1222 ASSERT_NE(mInputReceiver, nullptr)
1223 << "Cannot consume events from a window with no receiver";
1224 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1225 }
1226
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001227 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001228 if (mInputReceiver == nullptr) {
1229 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1230 return std::nullopt;
1231 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001232 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001233 }
1234
1235 void finishEvent(uint32_t sequenceNum) {
1236 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1237 mInputReceiver->finishEvent(sequenceNum);
1238 }
1239
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001240 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1241 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1242 mInputReceiver->sendTimeline(inputEventId, timeline);
1243 }
1244
chaviwaf87b3e2019-10-01 16:59:28 -07001245 InputEvent* consume() {
1246 if (mInputReceiver == nullptr) {
1247 return nullptr;
1248 }
1249 return mInputReceiver->consume();
1250 }
1251
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001252 MotionEvent* consumeMotion() {
1253 InputEvent* event = consume();
1254 if (event == nullptr) {
1255 ADD_FAILURE() << "Consume failed : no event";
1256 return nullptr;
1257 }
1258 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1259 ADD_FAILURE() << "Instead of motion event, got "
1260 << inputEventTypeToString(event->getType());
1261 return nullptr;
1262 }
1263 return static_cast<MotionEvent*>(event);
1264 }
1265
Arthur Hungb92218b2018-08-14 12:00:21 +08001266 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001267 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001268 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001269 return; // Can't receive events if the window does not have input channel
1270 }
1271 ASSERT_NE(nullptr, mInputReceiver)
1272 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001273 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001274 }
1275
chaviwaf87b3e2019-10-01 16:59:28 -07001276 sp<IBinder> getToken() { return mInfo.token; }
1277
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001278 const std::string& getName() { return mName; }
1279
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001280 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1281 mInfo.ownerPid = ownerPid;
1282 mInfo.ownerUid = ownerUid;
1283 }
1284
Prabir Pradhanedd96402022-02-15 01:46:16 -08001285 int32_t getPid() const { return mInfo.ownerPid; }
1286
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001287 void destroyReceiver() { mInputReceiver = nullptr; }
1288
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001289 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1290
chaviwd1c23182019-12-20 18:44:56 -08001291private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001292 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001293 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001294 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001295};
1296
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001297std::atomic<int32_t> FakeWindowHandle::sId{1};
1298
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001299static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001300 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001301 int32_t displayId = ADISPLAY_ID_NONE,
1302 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001303 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001304 bool allowKeyRepeat = true, std::optional<int32_t> targetUid = {},
1305 uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001306 KeyEvent event;
1307 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1308
1309 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001310 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001311 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1312 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001313
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001314 if (!allowKeyRepeat) {
1315 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1316 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001317 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001318 return dispatcher->injectInputEvent(&event, targetUid, syncMode, injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001319}
1320
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001321static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001322 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001323 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1324}
1325
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001326// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1327// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1328// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001329static InputEventInjectionResult injectKeyDownNoRepeat(
1330 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001331 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1332 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1333 /* allowKeyRepeat */ false);
1334}
1335
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001336static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001337 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001338 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1339}
1340
Garfield Tandf26e862020-07-01 20:18:19 -07001341class PointerBuilder {
1342public:
1343 PointerBuilder(int32_t id, int32_t toolType) {
1344 mProperties.clear();
1345 mProperties.id = id;
1346 mProperties.toolType = toolType;
1347 mCoords.clear();
1348 }
1349
1350 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1351
1352 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1353
1354 PointerBuilder& axis(int32_t axis, float value) {
1355 mCoords.setAxisValue(axis, value);
1356 return *this;
1357 }
1358
1359 PointerProperties buildProperties() const { return mProperties; }
1360
1361 PointerCoords buildCoords() const { return mCoords; }
1362
1363private:
1364 PointerProperties mProperties;
1365 PointerCoords mCoords;
1366};
1367
1368class MotionEventBuilder {
1369public:
1370 MotionEventBuilder(int32_t action, int32_t source) {
1371 mAction = action;
1372 mSource = source;
1373 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1374 }
1375
1376 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1377 mEventTime = eventTime;
1378 return *this;
1379 }
1380
1381 MotionEventBuilder& displayId(int32_t displayId) {
1382 mDisplayId = displayId;
1383 return *this;
1384 }
1385
1386 MotionEventBuilder& actionButton(int32_t actionButton) {
1387 mActionButton = actionButton;
1388 return *this;
1389 }
1390
arthurhung6d4bed92021-03-17 11:59:33 +08001391 MotionEventBuilder& buttonState(int32_t buttonState) {
1392 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001393 return *this;
1394 }
1395
1396 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1397 mRawXCursorPosition = rawXCursorPosition;
1398 return *this;
1399 }
1400
1401 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1402 mRawYCursorPosition = rawYCursorPosition;
1403 return *this;
1404 }
1405
1406 MotionEventBuilder& pointer(PointerBuilder pointer) {
1407 mPointers.push_back(pointer);
1408 return *this;
1409 }
1410
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001411 MotionEventBuilder& addFlag(uint32_t flags) {
1412 mFlags |= flags;
1413 return *this;
1414 }
1415
Garfield Tandf26e862020-07-01 20:18:19 -07001416 MotionEvent build() {
1417 std::vector<PointerProperties> pointerProperties;
1418 std::vector<PointerCoords> pointerCoords;
1419 for (const PointerBuilder& pointer : mPointers) {
1420 pointerProperties.push_back(pointer.buildProperties());
1421 pointerCoords.push_back(pointer.buildCoords());
1422 }
1423
1424 // Set mouse cursor position for the most common cases to avoid boilerplate.
1425 if (mSource == AINPUT_SOURCE_MOUSE &&
1426 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1427 mPointers.size() == 1) {
1428 mRawXCursorPosition = pointerCoords[0].getX();
1429 mRawYCursorPosition = pointerCoords[0].getY();
1430 }
1431
1432 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001433 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001434 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001435 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001436 mButtonState, MotionClassification::NONE, identityTransform,
1437 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001438 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1439 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001440
1441 return event;
1442 }
1443
1444private:
1445 int32_t mAction;
1446 int32_t mSource;
1447 nsecs_t mEventTime;
1448 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1449 int32_t mActionButton{0};
1450 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001451 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001452 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1453 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1454
1455 std::vector<PointerBuilder> mPointers;
1456};
1457
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001458static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001459 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001460 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001461 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
1462 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
1463 return dispatcher->injectInputEvent(&event, targetUid, injectionMode, injectionTimeout,
1464 policyFlags);
Garfield Tandf26e862020-07-01 20:18:19 -07001465}
1466
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001468 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001469 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001470 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001471 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1472 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001473 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan5735a322022-04-11 17:23:34 +00001474 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC),
1475 std::optional<int32_t> targetUid = {}, uint32_t policyFlags = DEFAULT_POLICY_FLAGS) {
Garfield Tandf26e862020-07-01 20:18:19 -07001476 MotionEvent event = MotionEventBuilder(action, source)
1477 .displayId(displayId)
1478 .eventTime(eventTime)
1479 .rawXCursorPosition(cursorPosition.x)
1480 .rawYCursorPosition(cursorPosition.y)
1481 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1482 .x(position.x)
1483 .y(position.y))
1484 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001485
1486 // Inject event until dispatch out.
Prabir Pradhan5735a322022-04-11 17:23:34 +00001487 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode, targetUid,
1488 policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001489}
1490
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001491static InputEventInjectionResult injectMotionDown(
1492 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1493 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001494 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001495}
1496
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001497static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001498 int32_t source, int32_t displayId,
1499 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001500 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001501}
1502
Jackal Guof9696682018-10-05 12:23:23 +08001503static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1504 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1505 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1507 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1508 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001509
1510 return args;
1511}
1512
chaviwd1c23182019-12-20 18:44:56 -08001513static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1514 const std::vector<PointF>& points) {
1515 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001516 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1517 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1518 }
1519
chaviwd1c23182019-12-20 18:44:56 -08001520 PointerProperties pointerProperties[pointerCount];
1521 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001522
chaviwd1c23182019-12-20 18:44:56 -08001523 for (size_t i = 0; i < pointerCount; i++) {
1524 pointerProperties[i].clear();
1525 pointerProperties[i].id = i;
1526 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001527
chaviwd1c23182019-12-20 18:44:56 -08001528 pointerCoords[i].clear();
1529 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1530 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1531 }
Jackal Guof9696682018-10-05 12:23:23 +08001532
1533 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1534 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001535 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001536 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1537 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001538 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1539 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001540 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1541 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001542
1543 return args;
1544}
1545
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001546static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1547 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1548}
1549
chaviwd1c23182019-12-20 18:44:56 -08001550static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1551 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1552}
1553
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001554static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1555 const PointerCaptureRequest& request) {
1556 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001557}
1558
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001559/**
1560 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1561 * broken channel.
1562 */
1563TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1564 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1565 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001566 sp<FakeWindowHandle>::make(application, mDispatcher,
1567 "Window that breaks its input channel", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001568
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1570
1571 // Window closes its channel, but the window remains.
1572 window->destroyReceiver();
1573 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1574}
1575
Arthur Hungb92218b2018-08-14 12:00:21 +08001576TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001577 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001578 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1579 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001580
Arthur Hung72d8dc32020-03-28 00:48:39 +00001581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001585
1586 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001587 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001588}
1589
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001590TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1591 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001592 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1593 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001594
1595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1596 // Inject a MotionEvent to an unknown display.
1597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1600
1601 // Window should receive motion event.
1602 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1603}
1604
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001605/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001606 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001607 * This test serves as a sanity check for the next test, where setInputWindows is
1608 * called twice.
1609 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001610TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001611 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001612 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1613 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001614 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1619 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001621
1622 // Window should receive motion event.
1623 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1624}
1625
1626/**
1627 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001628 */
1629TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001630 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001631 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
1632 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001633 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001634
1635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001638 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1639 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001641
1642 // Window should receive motion event.
1643 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1644}
1645
Arthur Hungb92218b2018-08-14 12:00:21 +08001646// The foreground window should receive the first touch down event.
1647TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001649 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001650 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001651 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001652 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001653
Arthur Hung72d8dc32020-03-28 00:48:39 +00001654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1657 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001658
1659 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001660 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001661 windowSecond->assertNoEvents();
1662}
1663
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001664/**
1665 * Two windows: A top window, and a wallpaper behind the window.
1666 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1667 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001668 * 1. foregroundWindow <-- dup touch to wallpaper
1669 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001670 */
1671TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1672 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1673 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001674 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001675 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001676 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001677 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001678 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001679 constexpr int expectedWallpaperFlags =
1680 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1681
1682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1684 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1685 {100, 200}))
1686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1687
1688 // Both foreground window and its wallpaper should receive the touch down
1689 foregroundWindow->consumeMotionDown();
1690 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1691
1692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1693 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1694 ADISPLAY_ID_DEFAULT, {110, 200}))
1695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1696
1697 foregroundWindow->consumeMotionMove();
1698 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1699
1700 // Now the foreground window goes away, but the wallpaper stays
1701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1702 foregroundWindow->consumeMotionCancel();
1703 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1704 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1705}
1706
1707/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001708 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1709 * with the following differences:
1710 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1711 * clean up the connection.
1712 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1713 * Ensure that there's no crash in the dispatcher.
1714 */
1715TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1716 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1717 sp<FakeWindowHandle> foregroundWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001718 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001719 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001720 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001721 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001722 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001723 constexpr int expectedWallpaperFlags =
1724 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1725
1726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1729 {100, 200}))
1730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1731
1732 // Both foreground window and its wallpaper should receive the touch down
1733 foregroundWindow->consumeMotionDown();
1734 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1735
1736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1737 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1738 ADISPLAY_ID_DEFAULT, {110, 200}))
1739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1740
1741 foregroundWindow->consumeMotionMove();
1742 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1743
1744 // Wallpaper closes its channel, but the window remains.
1745 wallpaperWindow->destroyReceiver();
1746 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1747
1748 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1749 // is no longer valid.
1750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1751 foregroundWindow->consumeMotionCancel();
1752}
1753
1754/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001755 * A single window that receives touch (on top), and a wallpaper window underneath it.
1756 * The top window gets a multitouch gesture.
1757 * Ensure that wallpaper gets the same gesture.
1758 */
1759TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1761 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001762 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001763 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001764
1765 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001766 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001767 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001768 constexpr int expectedWallpaperFlags =
1769 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1770
1771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1772
1773 // Touch down on top window
1774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1776 {100, 100}))
1777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1778
1779 // Both top window and its wallpaper should receive the touch down
1780 window->consumeMotionDown();
1781 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1782
1783 // Second finger down on the top window
1784 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001785 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001786 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1787 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1788 .x(100)
1789 .y(100))
1790 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1791 .x(150)
1792 .y(150))
1793 .build();
1794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1795 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1796 InputEventInjectionSync::WAIT_FOR_RESULT))
1797 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1798
1799 window->consumeMotionPointerDown(1 /* pointerIndex */);
1800 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1801 expectedWallpaperFlags);
1802 window->assertNoEvents();
1803 wallpaperWindow->assertNoEvents();
1804}
1805
1806/**
1807 * Two windows: a window on the left and window on the right.
1808 * A third window, wallpaper, is behind both windows, and spans both top windows.
1809 * The first touch down goes to the left window. A second pointer touches down on the right window.
1810 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1811 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1812 * ACTION_POINTER_DOWN(1).
1813 */
1814TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1815 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1816 sp<FakeWindowHandle> leftWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001817 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001818 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001819 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001820
1821 sp<FakeWindowHandle> rightWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001822 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001823 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001824 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001825
1826 sp<FakeWindowHandle> wallpaperWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001827 sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001828 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001829 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001830 constexpr int expectedWallpaperFlags =
1831 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1832
1833 mDispatcher->setInputWindows(
1834 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1835
1836 // Touch down on left window
1837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1839 {100, 100}))
1840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1841
1842 // Both foreground window and its wallpaper should receive the touch down
1843 leftWindow->consumeMotionDown();
1844 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1845
1846 // Second finger down on the right window
1847 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001848 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001849 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1850 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1851 .x(100)
1852 .y(100))
1853 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1854 .x(300)
1855 .y(100))
1856 .build();
1857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1858 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1859 InputEventInjectionSync::WAIT_FOR_RESULT))
1860 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1861
1862 leftWindow->consumeMotionMove();
1863 // Since the touch is split, right window gets ACTION_DOWN
1864 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1865 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1866 expectedWallpaperFlags);
1867
1868 // Now, leftWindow, which received the first finger, disappears.
1869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1870 leftWindow->consumeMotionCancel();
1871 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1872 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1873
1874 // The pointer that's still down on the right window moves, and goes to the right window only.
1875 // As far as the dispatcher's concerned though, both pointers are still present.
1876 const MotionEvent secondFingerMoveEvent =
1877 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1878 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1879 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1880 .x(100)
1881 .y(100))
1882 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1883 .x(310)
1884 .y(110))
1885 .build();
1886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1887 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1888 InputEventInjectionSync::WAIT_FOR_RESULT));
1889 rightWindow->consumeMotionMove();
1890
1891 leftWindow->assertNoEvents();
1892 rightWindow->assertNoEvents();
1893 wallpaperWindow->assertNoEvents();
1894}
1895
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001896/**
1897 * On the display, have a single window, and also an area where there's no window.
1898 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1899 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1900 */
1901TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1902 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1903 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001904 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001905
1906 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1907 NotifyMotionArgs args;
1908
1909 // Touch down on the empty space
1910 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1911
1912 mDispatcher->waitForIdle();
1913 window->assertNoEvents();
1914
1915 // Now touch down on the window with another pointer
1916 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1917 mDispatcher->waitForIdle();
1918 window->consumeMotionDown();
1919}
1920
1921/**
1922 * Same test as above, but instead of touching the empty space, the first touch goes to
1923 * non-touchable window.
1924 */
1925TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1927 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001928 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001929 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1930 window1->setTouchable(false);
1931 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001932 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001933 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1934
1935 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1936
1937 NotifyMotionArgs args;
1938 // Touch down on the non-touchable window
1939 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1940
1941 mDispatcher->waitForIdle();
1942 window1->assertNoEvents();
1943 window2->assertNoEvents();
1944
1945 // Now touch down on the window with another pointer
1946 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1947 mDispatcher->waitForIdle();
1948 window2->consumeMotionDown();
1949}
1950
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001951/**
1952 * When splitting touch events the downTime should be adjusted such that the downTime corresponds
1953 * to the event time of the first ACTION_DOWN sent to the particular window.
1954 */
1955TEST_F(InputDispatcherTest, SplitTouchesSendCorrectActionDownTime) {
1956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1957 sp<FakeWindowHandle> window1 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001958 sp<FakeWindowHandle>::make(application, mDispatcher, "Window1", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001959 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1960 sp<FakeWindowHandle> window2 =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07001961 sp<FakeWindowHandle>::make(application, mDispatcher, "Window2", DISPLAY_ID);
Vaibhav Devmurari882bd9b2022-06-23 14:54:54 +00001962 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1963
1964 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1965
1966 NotifyMotionArgs args;
1967 // Touch down on the first window
1968 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1969
1970 mDispatcher->waitForIdle();
1971 InputEvent* inputEvent1 = window1->consume();
1972 window2->assertNoEvents();
1973 MotionEvent& motionEvent1 = static_cast<MotionEvent&>(*inputEvent1);
1974 nsecs_t downTimeForWindow1 = motionEvent1.getDownTime();
1975 ASSERT_EQ(motionEvent1.getDownTime(), motionEvent1.getEventTime());
1976
1977 // Now touch down on the window with another pointer
1978 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1979 mDispatcher->waitForIdle();
1980 InputEvent* inputEvent2 = window2->consume();
1981 MotionEvent& motionEvent2 = static_cast<MotionEvent&>(*inputEvent2);
1982 nsecs_t downTimeForWindow2 = motionEvent2.getDownTime();
1983 ASSERT_NE(downTimeForWindow1, downTimeForWindow2);
1984 ASSERT_EQ(motionEvent2.getDownTime(), motionEvent2.getEventTime());
1985
1986 // Now move the pointer on the second window
1987 mDispatcher->notifyMotion(
1988 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{50, 50}, {151, 51}})));
1989 mDispatcher->waitForIdle();
1990 InputEvent* inputEvent3 = window2->consume();
1991 MotionEvent& motionEvent3 = static_cast<MotionEvent&>(*inputEvent3);
1992 ASSERT_EQ(motionEvent3.getDownTime(), downTimeForWindow2);
1993
1994 // Now add new touch down on the second window
1995 mDispatcher->notifyMotion(
1996 &(args = generateTouchArgs(POINTER_2_DOWN, {{50, 50}, {151, 51}, {150, 50}})));
1997 mDispatcher->waitForIdle();
1998 InputEvent* inputEvent4 = window2->consume();
1999 MotionEvent& motionEvent4 = static_cast<MotionEvent&>(*inputEvent4);
2000 ASSERT_EQ(motionEvent4.getDownTime(), downTimeForWindow2);
2001
2002 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
2003 window1->consumeMotionMove();
2004 window1->assertNoEvents();
2005
2006 // Now move the pointer on the first window
2007 mDispatcher->notifyMotion(
2008 &(args = generateTouchArgs(AMOTION_EVENT_ACTION_MOVE, {{51, 51}, {151, 51}})));
2009 mDispatcher->waitForIdle();
2010 InputEvent* inputEvent5 = window1->consume();
2011 MotionEvent& motionEvent5 = static_cast<MotionEvent&>(*inputEvent5);
2012 ASSERT_EQ(motionEvent5.getDownTime(), downTimeForWindow1);
2013
2014 mDispatcher->notifyMotion(&(
2015 args = generateTouchArgs(POINTER_3_DOWN, {{51, 51}, {151, 51}, {150, 50}, {50, 50}})));
2016 mDispatcher->waitForIdle();
2017 InputEvent* inputEvent6 = window1->consume();
2018 MotionEvent& motionEvent6 = static_cast<MotionEvent&>(*inputEvent6);
2019 ASSERT_EQ(motionEvent6.getDownTime(), downTimeForWindow1);
2020}
2021
Garfield Tandf26e862020-07-01 20:18:19 -07002022TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002023 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002024 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002025 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002026 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002027 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002028 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002029 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002030
2031 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2032
2033 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
2034
2035 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002037 injectMotionEvent(mDispatcher,
2038 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2039 AINPUT_SOURCE_MOUSE)
2040 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2041 .x(900)
2042 .y(400))
2043 .build()));
2044 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2045 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2046 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2047 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2048
2049 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002051 injectMotionEvent(mDispatcher,
2052 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2053 AINPUT_SOURCE_MOUSE)
2054 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2055 .x(300)
2056 .y(400))
2057 .build()));
2058 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2059 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2060 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2061 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2062 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2063 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2064
2065 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002067 injectMotionEvent(mDispatcher,
2068 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2069 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2070 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2071 .x(300)
2072 .y(400))
2073 .build()));
2074 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2075
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002077 injectMotionEvent(mDispatcher,
2078 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2079 AINPUT_SOURCE_MOUSE)
2080 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2081 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2082 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2083 .x(300)
2084 .y(400))
2085 .build()));
2086 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2087 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2088
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002090 injectMotionEvent(mDispatcher,
2091 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2092 AINPUT_SOURCE_MOUSE)
2093 .buttonState(0)
2094 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2095 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2096 .x(300)
2097 .y(400))
2098 .build()));
2099 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2100 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002103 injectMotionEvent(mDispatcher,
2104 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2105 .buttonState(0)
2106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2107 .x(300)
2108 .y(400))
2109 .build()));
2110 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2111
2112 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002114 injectMotionEvent(mDispatcher,
2115 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2116 AINPUT_SOURCE_MOUSE)
2117 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2118 .x(900)
2119 .y(400))
2120 .build()));
2121 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2122 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2123 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2124 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2125 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2126 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2127}
2128
2129// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2130// directly in this test.
2131TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002132 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002133 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002134 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Garfield Tandf26e862020-07-01 20:18:19 -07002135 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002136
2137 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2138
2139 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2140
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002142 injectMotionEvent(mDispatcher,
2143 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2144 AINPUT_SOURCE_MOUSE)
2145 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2146 .x(300)
2147 .y(400))
2148 .build()));
2149 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2150 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2151
2152 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002154 injectMotionEvent(mDispatcher,
2155 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2156 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2157 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2158 .x(300)
2159 .y(400))
2160 .build()));
2161 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2162
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002163 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002164 injectMotionEvent(mDispatcher,
2165 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2166 AINPUT_SOURCE_MOUSE)
2167 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2168 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2169 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2170 .x(300)
2171 .y(400))
2172 .build()));
2173 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2174 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2175
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002176 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002177 injectMotionEvent(mDispatcher,
2178 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2179 AINPUT_SOURCE_MOUSE)
2180 .buttonState(0)
2181 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2182 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2183 .x(300)
2184 .y(400))
2185 .build()));
2186 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2187 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2188
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002189 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002190 injectMotionEvent(mDispatcher,
2191 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2192 .buttonState(0)
2193 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2194 .x(300)
2195 .y(400))
2196 .build()));
2197 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2198
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002200 injectMotionEvent(mDispatcher,
2201 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2202 AINPUT_SOURCE_MOUSE)
2203 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2204 .x(300)
2205 .y(400))
2206 .build()));
2207 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2208 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2209}
2210
Garfield Tan00f511d2019-06-12 16:55:40 -07002211TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002212 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002213
2214 sp<FakeWindowHandle> windowLeft =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002215 sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002216 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002217 sp<FakeWindowHandle> windowRight =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002218 sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002219 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002220
2221 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2222
Arthur Hung72d8dc32020-03-28 00:48:39 +00002223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002224
2225 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2226 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002228 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002229 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002230 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002231 windowRight->assertNoEvents();
2232}
2233
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002234TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002235 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002236 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2237 "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002238 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002239
Arthur Hung72d8dc32020-03-28 00:48:39 +00002240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002241 setFocusedWindow(window);
2242
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002243 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002244
2245 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2246 mDispatcher->notifyKey(&keyArgs);
2247
2248 // Window should receive key down event.
2249 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2250
2251 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2252 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002253 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002254 mDispatcher->notifyDeviceReset(&args);
2255 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2256 AKEY_EVENT_FLAG_CANCELED);
2257}
2258
2259TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002260 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002261 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2262 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002263
Arthur Hung72d8dc32020-03-28 00:48:39 +00002264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002265
2266 NotifyMotionArgs motionArgs =
2267 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2268 ADISPLAY_ID_DEFAULT);
2269 mDispatcher->notifyMotion(&motionArgs);
2270
2271 // Window should receive motion down event.
2272 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2273
2274 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2275 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002276 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002277 mDispatcher->notifyDeviceReset(&args);
2278 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2279 0 /*expectedFlags*/);
2280}
2281
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002282TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002284 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2285 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002286 window->setFocusable(true);
2287
2288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2289 setFocusedWindow(window);
2290
2291 window->consumeFocusEvent(true);
2292
2293 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2294 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2295 const nsecs_t injectTime = keyArgs.eventTime;
2296 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2297 mDispatcher->notifyKey(&keyArgs);
2298 // The dispatching time should be always greater than or equal to intercept key timeout.
2299 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2300 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2301 std::chrono::nanoseconds(interceptKeyTimeout).count());
2302}
2303
2304TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2305 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002306 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2307 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002308 window->setFocusable(true);
2309
2310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2311 setFocusedWindow(window);
2312
2313 window->consumeFocusEvent(true);
2314
2315 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2316 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2317 mFakePolicy->setInterceptKeyTimeout(150ms);
2318 mDispatcher->notifyKey(&keyDown);
2319 mDispatcher->notifyKey(&keyUp);
2320
2321 // Window should receive key event immediately when same key up.
2322 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2323 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2324}
2325
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002326/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002327 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2328 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2329 * ACTION_OUTSIDE event is sent per gesture.
2330 */
2331TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2332 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2333 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002334 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2335 "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002336 window->setWatchOutsideTouch(true);
2337 window->setFrame(Rect{0, 0, 100, 100});
2338 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002339 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2340 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002341 secondWindow->setFrame(Rect{100, 100, 200, 200});
2342 sp<FakeWindowHandle> thirdWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002343 sp<FakeWindowHandle>::make(application, mDispatcher, "Third Window",
2344 ADISPLAY_ID_DEFAULT);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002345 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2347
2348 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2349 NotifyMotionArgs motionArgs =
2350 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2351 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2352 mDispatcher->notifyMotion(&motionArgs);
2353 window->assertNoEvents();
2354 secondWindow->assertNoEvents();
2355
2356 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2357 // Now, `window` should get ACTION_OUTSIDE.
2358 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2359 {PointF{-10, -10}, PointF{105, 105}});
2360 mDispatcher->notifyMotion(&motionArgs);
2361 window->consumeMotionOutside();
2362 secondWindow->consumeMotionDown();
2363 thirdWindow->assertNoEvents();
2364
2365 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2366 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2367 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2368 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2369 mDispatcher->notifyMotion(&motionArgs);
2370 window->assertNoEvents();
2371 secondWindow->consumeMotionMove();
2372 thirdWindow->consumeMotionDown();
2373}
2374
Prabir Pradhan814fe082022-07-22 20:22:18 +00002375TEST_F(InputDispatcherTest, OnWindowInfosChanged_RemoveAllWindowsOnDisplay) {
2376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002377 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2378 "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan814fe082022-07-22 20:22:18 +00002379 window->setFocusable(true);
2380
2381 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {});
2382 setFocusedWindow(window);
2383
2384 window->consumeFocusEvent(true);
2385
2386 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2387 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2388 mDispatcher->notifyKey(&keyDown);
2389 mDispatcher->notifyKey(&keyUp);
2390
2391 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2392 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2393
2394 // All windows are removed from the display. Ensure that we can no longer dispatch to it.
2395 mDispatcher->onWindowInfosChanged({}, {});
2396
2397 window->consumeFocusEvent(false);
2398
2399 mDispatcher->notifyKey(&keyDown);
2400 mDispatcher->notifyKey(&keyUp);
2401 window->assertNoEvents();
2402}
2403
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002404/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002405 * Ensure the correct coordinate spaces are used by InputDispatcher.
2406 *
2407 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2408 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2409 * space.
2410 */
2411class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2412public:
2413 void SetUp() override {
2414 InputDispatcherTest::SetUp();
2415 mDisplayInfos.clear();
2416 mWindowInfos.clear();
2417 }
2418
2419 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2420 gui::DisplayInfo info;
2421 info.displayId = displayId;
2422 info.transform = transform;
2423 mDisplayInfos.push_back(std::move(info));
2424 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2425 }
2426
2427 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2428 mWindowInfos.push_back(*windowHandle->getInfo());
2429 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2430 }
2431
2432 // Set up a test scenario where the display has a scaled projection and there are two windows
2433 // on the display.
2434 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2435 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2436 // respectively.
2437 ui::Transform displayTransform;
2438 displayTransform.set(2, 0, 0, 4);
2439 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2440
2441 std::shared_ptr<FakeApplicationHandle> application =
2442 std::make_shared<FakeApplicationHandle>();
2443
2444 // Add two windows to the display. Their frames are represented in the display space.
2445 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002446 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2447 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002448 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2449 addWindow(firstWindow);
2450
2451 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002452 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2453 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002454 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2455 addWindow(secondWindow);
2456 return {std::move(firstWindow), std::move(secondWindow)};
2457 }
2458
2459private:
2460 std::vector<gui::DisplayInfo> mDisplayInfos;
2461 std::vector<gui::WindowInfo> mWindowInfos;
2462};
2463
2464TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2465 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2466 // Send down to the first window. The point is represented in the display space. The point is
2467 // selected so that if the hit test was done with the transform applied to it, then it would
2468 // end up in the incorrect window.
2469 NotifyMotionArgs downMotionArgs =
2470 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2471 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2472 mDispatcher->notifyMotion(&downMotionArgs);
2473
2474 firstWindow->consumeMotionDown();
2475 secondWindow->assertNoEvents();
2476}
2477
2478// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2479// the event should be treated as being in the logical display space.
2480TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2481 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2482 // Send down to the first window. The point is represented in the logical display space. The
2483 // point is selected so that if the hit test was done in logical display space, then it would
2484 // end up in the incorrect window.
2485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2486 PointF{75 * 2, 55 * 4});
2487
2488 firstWindow->consumeMotionDown();
2489 secondWindow->assertNoEvents();
2490}
2491
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002492// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2493// event should be treated as being in the logical display space.
2494TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2495 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2496
2497 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2498 ui::Transform injectedEventTransform;
2499 injectedEventTransform.set(matrix);
2500 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2501 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2502
2503 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2504 .displayId(ADISPLAY_ID_DEFAULT)
2505 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2506 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2507 .x(untransformedPoint.x)
2508 .y(untransformedPoint.y))
2509 .build();
2510 event.transform(matrix);
2511
2512 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2513 InputEventInjectionSync::WAIT_FOR_RESULT);
2514
2515 firstWindow->consumeMotionDown();
2516 secondWindow->assertNoEvents();
2517}
2518
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002519TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2520 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2521
2522 // Send down to the second window.
2523 NotifyMotionArgs downMotionArgs =
2524 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2525 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2526 mDispatcher->notifyMotion(&downMotionArgs);
2527
2528 firstWindow->assertNoEvents();
2529 const MotionEvent* event = secondWindow->consumeMotion();
2530 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2531
2532 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2533 EXPECT_EQ(300, event->getRawX(0));
2534 EXPECT_EQ(880, event->getRawY(0));
2535
2536 // Ensure that the x and y values are in the window's coordinate space.
2537 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2538 // the logical display space. This will be the origin of the window space.
2539 EXPECT_EQ(100, event->getX(0));
2540 EXPECT_EQ(80, event->getY(0));
2541}
2542
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002543using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2544 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002545
2546class TransferTouchFixture : public InputDispatcherTest,
2547 public ::testing::WithParamInterface<TransferFunction> {};
2548
2549TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002550 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002551
2552 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002553 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002554 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2555 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002556 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002557 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2558 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002559
2560 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002562
2563 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002564 NotifyMotionArgs downMotionArgs =
2565 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2566 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002567 mDispatcher->notifyMotion(&downMotionArgs);
2568 // Only the first window should get the down event
2569 firstWindow->consumeMotionDown();
2570 secondWindow->assertNoEvents();
2571
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002572 // Transfer touch to the second window
2573 TransferFunction f = GetParam();
2574 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2575 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002576 // The first window gets cancel and the second gets down
2577 firstWindow->consumeMotionCancel();
2578 secondWindow->consumeMotionDown();
2579
2580 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002581 NotifyMotionArgs upMotionArgs =
2582 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2583 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002584 mDispatcher->notifyMotion(&upMotionArgs);
2585 // The first window gets no events and the second gets up
2586 firstWindow->assertNoEvents();
2587 secondWindow->consumeMotionUp();
2588}
2589
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002590/**
2591 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2592 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2593 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2594 * natural to the user.
2595 * In this test, we are sending a pointer to both spy window and first window. We then try to
2596 * transfer touch to the second window. The dispatcher should identify the first window as the
2597 * one that should lose the gesture, and therefore the action should be to move the gesture from
2598 * the first window to the second.
2599 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2600 * the other API, as well.
2601 */
2602TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2603 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2604
2605 // Create a couple of windows + a spy window
2606 sp<FakeWindowHandle> spyWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002607 sp<FakeWindowHandle>::make(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002608 spyWindow->setTrustedOverlay(true);
2609 spyWindow->setSpy(true);
2610 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002611 sp<FakeWindowHandle>::make(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002612 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002613 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002614
2615 // Add the windows to the dispatcher
2616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2617
2618 // Send down to the first window
2619 NotifyMotionArgs downMotionArgs =
2620 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2621 ADISPLAY_ID_DEFAULT);
2622 mDispatcher->notifyMotion(&downMotionArgs);
2623 // Only the first window and spy should get the down event
2624 spyWindow->consumeMotionDown();
2625 firstWindow->consumeMotionDown();
2626
2627 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2628 // if f === 'transferTouch'.
2629 TransferFunction f = GetParam();
2630 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2631 ASSERT_TRUE(success);
2632 // The first window gets cancel and the second gets down
2633 firstWindow->consumeMotionCancel();
2634 secondWindow->consumeMotionDown();
2635
2636 // Send up event to the second window
2637 NotifyMotionArgs upMotionArgs =
2638 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2639 ADISPLAY_ID_DEFAULT);
2640 mDispatcher->notifyMotion(&upMotionArgs);
2641 // The first window gets no events and the second+spy get up
2642 firstWindow->assertNoEvents();
2643 spyWindow->consumeMotionUp();
2644 secondWindow->consumeMotionUp();
2645}
2646
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002647TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002648 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002649
2650 PointF touchPoint = {10, 10};
2651
2652 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002653 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002654 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2655 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002656 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002657 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002658 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2659 ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002660 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002661
2662 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002664
2665 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002666 NotifyMotionArgs downMotionArgs =
2667 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2668 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002669 mDispatcher->notifyMotion(&downMotionArgs);
2670 // Only the first window should get the down event
2671 firstWindow->consumeMotionDown();
2672 secondWindow->assertNoEvents();
2673
2674 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002675 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002676 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002677 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002678 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2679 // Only the first window should get the pointer down event
2680 firstWindow->consumeMotionPointerDown(1);
2681 secondWindow->assertNoEvents();
2682
2683 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002684 TransferFunction f = GetParam();
2685 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2686 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002687 // The first window gets cancel and the second gets down and pointer down
2688 firstWindow->consumeMotionCancel();
2689 secondWindow->consumeMotionDown();
2690 secondWindow->consumeMotionPointerDown(1);
2691
2692 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002693 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002694 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002695 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002696 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2697 // The first window gets nothing and the second gets pointer up
2698 firstWindow->assertNoEvents();
2699 secondWindow->consumeMotionPointerUp(1);
2700
2701 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002702 NotifyMotionArgs upMotionArgs =
2703 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2704 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002705 mDispatcher->notifyMotion(&upMotionArgs);
2706 // The first window gets nothing and the second gets up
2707 firstWindow->assertNoEvents();
2708 secondWindow->consumeMotionUp();
2709}
2710
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002711// For the cases of single pointer touch and two pointers non-split touch, the api's
2712// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2713// for the case where there are multiple pointers split across several windows.
2714INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2715 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002716 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2717 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002718 return dispatcher->transferTouch(destChannelToken,
2719 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002720 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002721 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2722 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002723 return dispatcher->transferTouchFocus(from, to,
2724 false /*isDragAndDrop*/);
2725 }));
2726
Svet Ganov5d3bc372020-01-26 23:11:07 -08002727TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002728 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002729
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002730 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002731 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2732 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002733 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002734
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002735 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002736 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2737 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002738 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002739
2740 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002742
2743 PointF pointInFirst = {300, 200};
2744 PointF pointInSecond = {300, 600};
2745
2746 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002747 NotifyMotionArgs firstDownMotionArgs =
2748 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2749 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002750 mDispatcher->notifyMotion(&firstDownMotionArgs);
2751 // Only the first window should get the down event
2752 firstWindow->consumeMotionDown();
2753 secondWindow->assertNoEvents();
2754
2755 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002756 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002757 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002758 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002759 mDispatcher->notifyMotion(&secondDownMotionArgs);
2760 // The first window gets a move and the second a down
2761 firstWindow->consumeMotionMove();
2762 secondWindow->consumeMotionDown();
2763
2764 // Transfer touch focus to the second window
2765 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2766 // The first window gets cancel and the new gets pointer down (it already saw down)
2767 firstWindow->consumeMotionCancel();
2768 secondWindow->consumeMotionPointerDown(1);
2769
2770 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002771 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002772 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002773 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002774 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2775 // The first window gets nothing and the second gets pointer up
2776 firstWindow->assertNoEvents();
2777 secondWindow->consumeMotionPointerUp(1);
2778
2779 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002780 NotifyMotionArgs upMotionArgs =
2781 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2782 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002783 mDispatcher->notifyMotion(&upMotionArgs);
2784 // The first window gets nothing and the second gets up
2785 firstWindow->assertNoEvents();
2786 secondWindow->consumeMotionUp();
2787}
2788
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002789// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2790// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2791// touch is not supported, so the touch should continue on those windows and the transferred-to
2792// window should get nothing.
2793TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2794 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2795
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002796 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002797 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
2798 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002799 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002800
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002801 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002802 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
2803 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002804 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002805
2806 // Add the windows to the dispatcher
2807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2808
2809 PointF pointInFirst = {300, 200};
2810 PointF pointInSecond = {300, 600};
2811
2812 // Send down to the first window
2813 NotifyMotionArgs firstDownMotionArgs =
2814 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2815 ADISPLAY_ID_DEFAULT, {pointInFirst});
2816 mDispatcher->notifyMotion(&firstDownMotionArgs);
2817 // Only the first window should get the down event
2818 firstWindow->consumeMotionDown();
2819 secondWindow->assertNoEvents();
2820
2821 // Send down to the second window
2822 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002823 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002824 {pointInFirst, pointInSecond});
2825 mDispatcher->notifyMotion(&secondDownMotionArgs);
2826 // The first window gets a move and the second a down
2827 firstWindow->consumeMotionMove();
2828 secondWindow->consumeMotionDown();
2829
2830 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002831 const bool transferred =
2832 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002833 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2834 ASSERT_FALSE(transferred);
2835 firstWindow->assertNoEvents();
2836 secondWindow->assertNoEvents();
2837
2838 // The rest of the dispatch should proceed as normal
2839 // Send pointer up to the second window
2840 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002841 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002842 {pointInFirst, pointInSecond});
2843 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2844 // The first window gets MOVE and the second gets pointer up
2845 firstWindow->consumeMotionMove();
2846 secondWindow->consumeMotionUp();
2847
2848 // Send up event to the first window
2849 NotifyMotionArgs upMotionArgs =
2850 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2851 ADISPLAY_ID_DEFAULT);
2852 mDispatcher->notifyMotion(&upMotionArgs);
2853 // The first window gets nothing and the second gets up
2854 firstWindow->consumeMotionUp();
2855 secondWindow->assertNoEvents();
2856}
2857
Arthur Hungabbb9d82021-09-01 14:52:30 +00002858// This case will create two windows and one mirrored window on the default display and mirror
2859// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2860// the windows info of second display before default display.
2861TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2862 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2863 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002864 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002865 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002866 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002867 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002868 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002869
2870 sp<FakeWindowHandle> mirrorWindowInPrimary =
2871 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2872 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002873
2874 sp<FakeWindowHandle> firstWindowInSecondary =
2875 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2876 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002877
2878 sp<FakeWindowHandle> secondWindowInSecondary =
2879 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2880 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002881
2882 // Update window info, let it find window handle of second display first.
2883 mDispatcher->setInputWindows(
2884 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2885 {ADISPLAY_ID_DEFAULT,
2886 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2887
2888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2889 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2890 {50, 50}))
2891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2892
2893 // Window should receive motion event.
2894 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2895
2896 // Transfer touch focus
2897 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2898 secondWindowInPrimary->getToken()));
2899 // The first window gets cancel.
2900 firstWindowInPrimary->consumeMotionCancel();
2901 secondWindowInPrimary->consumeMotionDown();
2902
2903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2904 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2905 ADISPLAY_ID_DEFAULT, {150, 50}))
2906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2907 firstWindowInPrimary->assertNoEvents();
2908 secondWindowInPrimary->consumeMotionMove();
2909
2910 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2911 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2912 {150, 50}))
2913 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2914 firstWindowInPrimary->assertNoEvents();
2915 secondWindowInPrimary->consumeMotionUp();
2916}
2917
2918// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2919// 'transferTouch' api.
2920TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2921 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2922 sp<FakeWindowHandle> firstWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002923 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002924 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002925 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002926 sp<FakeWindowHandle>::make(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002927 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002928
2929 sp<FakeWindowHandle> mirrorWindowInPrimary =
2930 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2931 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002932
2933 sp<FakeWindowHandle> firstWindowInSecondary =
2934 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2935 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002936
2937 sp<FakeWindowHandle> secondWindowInSecondary =
2938 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2939 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002940
2941 // Update window info, let it find window handle of second display first.
2942 mDispatcher->setInputWindows(
2943 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2944 {ADISPLAY_ID_DEFAULT,
2945 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2946
2947 // Touch on second display.
2948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2949 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2951
2952 // Window should receive motion event.
2953 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2954
2955 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002956 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002957
2958 // The first window gets cancel.
2959 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2960 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2961
2962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2963 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2964 SECOND_DISPLAY_ID, {150, 50}))
2965 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2966 firstWindowInPrimary->assertNoEvents();
2967 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2968
2969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2970 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2972 firstWindowInPrimary->assertNoEvents();
2973 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2974}
2975
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002976TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002977 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002978 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2979 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002980
Vishnu Nair47074b82020-08-14 11:54:47 -07002981 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002983 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002984
2985 window->consumeFocusEvent(true);
2986
2987 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2988 mDispatcher->notifyKey(&keyArgs);
2989
2990 // Window should receive key down event.
2991 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2992}
2993
2994TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07002996 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
2997 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002998
Arthur Hung72d8dc32020-03-28 00:48:39 +00002999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003000
3001 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3002 mDispatcher->notifyKey(&keyArgs);
3003 mDispatcher->waitForIdle();
3004
3005 window->assertNoEvents();
3006}
3007
3008// If a window is touchable, but does not have focus, it should receive motion events, but not keys
3009TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07003010 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003011 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3012 "Fake Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003013
Arthur Hung72d8dc32020-03-28 00:48:39 +00003014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003015
3016 // Send key
3017 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
3018 mDispatcher->notifyKey(&keyArgs);
3019 // Send motion
3020 NotifyMotionArgs motionArgs =
3021 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3022 ADISPLAY_ID_DEFAULT);
3023 mDispatcher->notifyMotion(&motionArgs);
3024
3025 // Window should receive only the motion event
3026 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3027 window->assertNoEvents(); // Key event or focus event will not be received
3028}
3029
arthurhungea3f4fc2020-12-21 23:18:53 +08003030TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
3031 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3032
arthurhungea3f4fc2020-12-21 23:18:53 +08003033 sp<FakeWindowHandle> firstWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003034 sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
3035 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003036 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08003037
arthurhungea3f4fc2020-12-21 23:18:53 +08003038 sp<FakeWindowHandle> secondWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003039 sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
3040 ADISPLAY_ID_DEFAULT);
arthurhungea3f4fc2020-12-21 23:18:53 +08003041 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08003042
3043 // Add the windows to the dispatcher
3044 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
3045
3046 PointF pointInFirst = {300, 200};
3047 PointF pointInSecond = {300, 600};
3048
3049 // Send down to the first window
3050 NotifyMotionArgs firstDownMotionArgs =
3051 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3052 ADISPLAY_ID_DEFAULT, {pointInFirst});
3053 mDispatcher->notifyMotion(&firstDownMotionArgs);
3054 // Only the first window should get the down event
3055 firstWindow->consumeMotionDown();
3056 secondWindow->assertNoEvents();
3057
3058 // Send down to the second window
3059 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003060 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003061 {pointInFirst, pointInSecond});
3062 mDispatcher->notifyMotion(&secondDownMotionArgs);
3063 // The first window gets a move and the second a down
3064 firstWindow->consumeMotionMove();
3065 secondWindow->consumeMotionDown();
3066
3067 // Send pointer cancel to the second window
3068 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08003069 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08003070 {pointInFirst, pointInSecond});
3071 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
3072 mDispatcher->notifyMotion(&pointerUpMotionArgs);
3073 // The first window gets move and the second gets cancel.
3074 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3075 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
3076
3077 // Send up event.
3078 NotifyMotionArgs upMotionArgs =
3079 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
3080 ADISPLAY_ID_DEFAULT);
3081 mDispatcher->notifyMotion(&upMotionArgs);
3082 // The first window gets up and the second gets nothing.
3083 firstWindow->consumeMotionUp();
3084 secondWindow->assertNoEvents();
3085}
3086
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003087TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
3088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3089
3090 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003091 sp<FakeWindowHandle>::make(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00003092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3093 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
3094 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
3095 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
3096
3097 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
3098 window->assertNoEvents();
3099 mDispatcher->waitForIdle();
3100}
3101
chaviwd1c23182019-12-20 18:44:56 -08003102class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00003103public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003104 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003105 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07003106 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08003107 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07003108 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00003109 }
3110
chaviwd1c23182019-12-20 18:44:56 -08003111 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
3112
3113 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3114 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
3115 expectedDisplayId, expectedFlags);
3116 }
3117
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07003118 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
3119
3120 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
3121
chaviwd1c23182019-12-20 18:44:56 -08003122 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3123 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
3124 expectedDisplayId, expectedFlags);
3125 }
3126
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003127 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3128 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
3129 expectedDisplayId, expectedFlags);
3130 }
3131
chaviwd1c23182019-12-20 18:44:56 -08003132 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3133 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
3134 expectedDisplayId, expectedFlags);
3135 }
3136
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003137 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
3138 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
3139 expectedDisplayId, expectedFlags);
3140 }
3141
Arthur Hungfbfa5722021-11-16 02:45:54 +00003142 void consumeMotionPointerDown(int32_t pointerIdx) {
3143 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
3144 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
3145 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
3146 0 /*expectedFlags*/);
3147 }
3148
Evan Rosky84f07f02021-04-16 10:42:42 -07003149 MotionEvent* consumeMotion() {
3150 InputEvent* event = mInputReceiver->consume();
3151 if (!event) {
3152 ADD_FAILURE() << "No event was produced";
3153 return nullptr;
3154 }
3155 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
3156 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
3157 return nullptr;
3158 }
3159 return static_cast<MotionEvent*>(event);
3160 }
3161
chaviwd1c23182019-12-20 18:44:56 -08003162 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
3163
3164private:
3165 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00003166};
3167
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003168using InputDispatcherMonitorTest = InputDispatcherTest;
3169
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003170/**
3171 * Two entities that receive touch: A window, and a global monitor.
3172 * The touch goes to the window, and then the window disappears.
3173 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3174 * for the monitor, as well.
3175 * 1. foregroundWindow
3176 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3177 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003178TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3180 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003181 sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003182
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003183 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003184
3185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3187 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3188 {100, 200}))
3189 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3190
3191 // Both the foreground window and the global monitor should receive the touch down
3192 window->consumeMotionDown();
3193 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3194
3195 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3196 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3197 ADISPLAY_ID_DEFAULT, {110, 200}))
3198 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3199
3200 window->consumeMotionMove();
3201 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3202
3203 // Now the foreground window goes away
3204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3205 window->consumeMotionCancel();
3206 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3207
3208 // If more events come in, there will be no more foreground window to send them to. This will
3209 // cause a cancel for the monitor, as well.
3210 ASSERT_EQ(InputEventInjectionResult::FAILED,
3211 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3212 ADISPLAY_ID_DEFAULT, {120, 200}))
3213 << "Injection should fail because the window was removed";
3214 window->assertNoEvents();
3215 // Global monitor now gets the cancel
3216 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3217}
3218
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003219TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003220 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003221 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3222 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003224
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003225 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003226
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003228 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003229 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003230 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003231 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003232}
3233
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003234TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3235 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003236
Chris Yea209fde2020-07-22 13:54:51 -07003237 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003238 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3239 "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003241
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003243 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003244 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003245 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003246 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003247
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003248 // Pilfer pointers from the monitor.
3249 // This should not do anything and the window should continue to receive events.
3250 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003251
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003253 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3254 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003255 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003256
3257 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3258 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003259}
3260
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003261TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003262 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003263 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3264 "Fake Window", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3266 window->setWindowOffset(20, 40);
3267 window->setWindowTransform(0, 1, -1, 0);
3268
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003269 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003270
3271 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3272 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3273 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3274 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3275 MotionEvent* event = monitor.consumeMotion();
3276 // Even though window has transform, gesture monitor must not.
3277 ASSERT_EQ(ui::Transform(), event->getTransform());
3278}
3279
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003280TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003282 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003283
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003284 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003285 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003286 << "Injection should fail if there is a monitor, but no touchable window";
3287 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003288}
3289
chaviw81e2bb92019-12-18 15:03:51 -08003290TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003292 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3293 "Fake Window", ADISPLAY_ID_DEFAULT);
chaviw81e2bb92019-12-18 15:03:51 -08003294
Arthur Hung72d8dc32020-03-28 00:48:39 +00003295 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003296
3297 NotifyMotionArgs motionArgs =
3298 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3299 ADISPLAY_ID_DEFAULT);
3300
3301 mDispatcher->notifyMotion(&motionArgs);
3302 // Window should receive motion down event.
3303 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3304
3305 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003306 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003307 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3308 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3309 motionArgs.pointerCoords[0].getX() - 10);
3310
3311 mDispatcher->notifyMotion(&motionArgs);
3312 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3313 0 /*expectedFlags*/);
3314}
3315
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003316/**
3317 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3318 * the device default right away. In the test scenario, we check both the default value,
3319 * and the action of enabling / disabling.
3320 */
3321TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003322 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003323 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3324 "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003325 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003326
3327 // Set focused application.
3328 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003329 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003330
3331 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003333 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003334 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3335
3336 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003337 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003339 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3340
3341 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003342 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003343 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003344 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003345 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003347 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003348 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3349
3350 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003351 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003353 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3354
3355 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003356 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07003357 true /*hasPermission*/, ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003358 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003359 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003361 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003362 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3363
3364 window->assertNoEvents();
3365}
3366
Gang Wange9087892020-01-07 12:17:14 -05003367TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003368 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003369 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3370 "Test window", ADISPLAY_ID_DEFAULT);
Gang Wange9087892020-01-07 12:17:14 -05003371
3372 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003373 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003374
Arthur Hung72d8dc32020-03-28 00:48:39 +00003375 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003376 setFocusedWindow(window);
3377
Gang Wange9087892020-01-07 12:17:14 -05003378 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3379
3380 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3381 mDispatcher->notifyKey(&keyArgs);
3382
3383 InputEvent* event = window->consume();
3384 ASSERT_NE(event, nullptr);
3385
3386 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3387 ASSERT_NE(verified, nullptr);
3388 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3389
3390 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3391 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3392 ASSERT_EQ(keyArgs.source, verified->source);
3393 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3394
3395 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3396
3397 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003398 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003399 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003400 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3401 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3402 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3403 ASSERT_EQ(0, verifiedKey.repeatCount);
3404}
3405
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003406TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003407 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003408 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
3409 "Test window", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003410
3411 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3412
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003413 ui::Transform transform;
3414 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3415
3416 gui::DisplayInfo displayInfo;
3417 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3418 displayInfo.transform = transform;
3419
3420 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003421
3422 NotifyMotionArgs motionArgs =
3423 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3424 ADISPLAY_ID_DEFAULT);
3425 mDispatcher->notifyMotion(&motionArgs);
3426
3427 InputEvent* event = window->consume();
3428 ASSERT_NE(event, nullptr);
3429
3430 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3431 ASSERT_NE(verified, nullptr);
3432 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3433
3434 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3435 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3436 EXPECT_EQ(motionArgs.source, verified->source);
3437 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3438
3439 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3440
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003441 const vec2 rawXY =
3442 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3443 motionArgs.pointerCoords[0].getXYValue());
3444 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3445 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003446 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003447 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003448 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003449 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3450 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3451}
3452
chaviw09c8d2d2020-08-24 15:48:26 -07003453/**
3454 * Ensure that separate calls to sign the same data are generating the same key.
3455 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3456 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3457 * tests.
3458 */
3459TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3460 KeyEvent event = getTestKeyEvent();
3461 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3462
3463 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3464 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3465 ASSERT_EQ(hmac1, hmac2);
3466}
3467
3468/**
3469 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3470 */
3471TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3472 KeyEvent event = getTestKeyEvent();
3473 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3474 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3475
3476 verifiedEvent.deviceId += 1;
3477 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3478
3479 verifiedEvent.source += 1;
3480 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3481
3482 verifiedEvent.eventTimeNanos += 1;
3483 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3484
3485 verifiedEvent.displayId += 1;
3486 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3487
3488 verifiedEvent.action += 1;
3489 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3490
3491 verifiedEvent.downTimeNanos += 1;
3492 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3493
3494 verifiedEvent.flags += 1;
3495 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3496
3497 verifiedEvent.keyCode += 1;
3498 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3499
3500 verifiedEvent.scanCode += 1;
3501 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3502
3503 verifiedEvent.metaState += 1;
3504 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3505
3506 verifiedEvent.repeatCount += 1;
3507 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3508}
3509
Vishnu Nair958da932020-08-21 17:12:37 -07003510TEST_F(InputDispatcherTest, SetFocusedWindow) {
3511 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3512 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003513 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003514 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003515 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003516 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3517
3518 // Top window is also focusable but is not granted focus.
3519 windowTop->setFocusable(true);
3520 windowSecond->setFocusable(true);
3521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3522 setFocusedWindow(windowSecond);
3523
3524 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3526 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003527
3528 // Focused window should receive event.
3529 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3530 windowTop->assertNoEvents();
3531}
3532
3533TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3534 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3535 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003536 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003537 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3538
3539 window->setFocusable(true);
3540 // Release channel for window is no longer valid.
3541 window->releaseChannel();
3542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3543 setFocusedWindow(window);
3544
3545 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003546 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3547 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003548
3549 // window channel is invalid, so it should not receive any input event.
3550 window->assertNoEvents();
3551}
3552
3553TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3554 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3555 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003556 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003557 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003558 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3559
Vishnu Nair958da932020-08-21 17:12:37 -07003560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3561 setFocusedWindow(window);
3562
3563 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003564 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3565 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003566
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003567 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003568 window->assertNoEvents();
3569}
3570
3571TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3572 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3573 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003574 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003575 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003576 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003577 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3578
3579 windowTop->setFocusable(true);
3580 windowSecond->setFocusable(true);
3581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3582 setFocusedWindow(windowTop);
3583 windowTop->consumeFocusEvent(true);
3584
3585 setFocusedWindow(windowSecond, windowTop);
3586 windowSecond->consumeFocusEvent(true);
3587 windowTop->consumeFocusEvent(false);
3588
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3590 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003591
3592 // Focused window should receive event.
3593 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3594}
3595
3596TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3597 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3598 sp<FakeWindowHandle> windowTop =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003599 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003600 sp<FakeWindowHandle> windowSecond =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003601 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003602 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3603
3604 windowTop->setFocusable(true);
3605 windowSecond->setFocusable(true);
3606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3607 setFocusedWindow(windowSecond, windowTop);
3608
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003609 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3610 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003611
3612 // Event should be dropped.
3613 windowTop->assertNoEvents();
3614 windowSecond->assertNoEvents();
3615}
3616
3617TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3618 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3619 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003620 sp<FakeWindowHandle>::make(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003621 sp<FakeWindowHandle> previousFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003622 sp<FakeWindowHandle>::make(application, mDispatcher, "previousFocusedWindow",
3623 ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07003624 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3625
3626 window->setFocusable(true);
3627 previousFocusedWindow->setFocusable(true);
3628 window->setVisible(false);
3629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3630 setFocusedWindow(previousFocusedWindow);
3631 previousFocusedWindow->consumeFocusEvent(true);
3632
3633 // Requesting focus on invisible window takes focus from currently focused window.
3634 setFocusedWindow(window);
3635 previousFocusedWindow->consumeFocusEvent(false);
3636
3637 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003639 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003640 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003641
3642 // Window does not get focus event or key down.
3643 window->assertNoEvents();
3644
3645 // Window becomes visible.
3646 window->setVisible(true);
3647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3648
3649 // Window receives focus event.
3650 window->consumeFocusEvent(true);
3651 // Focused window receives key down.
3652 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3653}
3654
Vishnu Nair599f1412021-06-21 10:39:58 -07003655TEST_F(InputDispatcherTest, DisplayRemoved) {
3656 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3657 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003658 sp<FakeWindowHandle>::make(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
Vishnu Nair599f1412021-06-21 10:39:58 -07003659 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3660
3661 // window is granted focus.
3662 window->setFocusable(true);
3663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3664 setFocusedWindow(window);
3665 window->consumeFocusEvent(true);
3666
3667 // When a display is removed window loses focus.
3668 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3669 window->consumeFocusEvent(false);
3670}
3671
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003672/**
3673 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3674 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3675 * of the 'slipperyEnterWindow'.
3676 *
3677 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3678 * a way so that the touched location is no longer covered by the top window.
3679 *
3680 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3681 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3682 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3683 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3684 * with ACTION_DOWN).
3685 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3686 * window moved itself away from the touched location and had Flag::SLIPPERY.
3687 *
3688 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3689 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3690 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3691 *
3692 * In this test, we ensure that the event received by the bottom window has
3693 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3694 */
3695TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan5735a322022-04-11 17:23:34 +00003696 constexpr int32_t SLIPPERY_PID = WINDOW_PID + 1;
3697 constexpr int32_t SLIPPERY_UID = WINDOW_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003698
3699 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3700 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3701
3702 sp<FakeWindowHandle> slipperyExitWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003703 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003704 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003705 // Make sure this one overlaps the bottom window
3706 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3707 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3708 // one. Windows with the same owner are not considered to be occluding each other.
3709 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3710
3711 sp<FakeWindowHandle> slipperyEnterWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003712 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003713 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3714
3715 mDispatcher->setInputWindows(
3716 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3717
3718 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3719 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3720 ADISPLAY_ID_DEFAULT, {{50, 50}});
3721 mDispatcher->notifyMotion(&args);
3722 slipperyExitWindow->consumeMotionDown();
3723 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3724 mDispatcher->setInputWindows(
3725 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3726
3727 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3728 ADISPLAY_ID_DEFAULT, {{51, 51}});
3729 mDispatcher->notifyMotion(&args);
3730
3731 slipperyExitWindow->consumeMotionCancel();
3732
3733 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3734 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3735}
3736
Garfield Tan1c7bc862020-01-28 13:24:04 -08003737class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3738protected:
3739 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3740 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3741
Chris Yea209fde2020-07-22 13:54:51 -07003742 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003743 sp<FakeWindowHandle> mWindow;
3744
3745 virtual void SetUp() override {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003746 mFakePolicy = sp<FakeInputDispatcherPolicy>::make();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003747 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003748 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003749 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3750 ASSERT_EQ(OK, mDispatcher->start());
3751
3752 setUpWindow();
3753 }
3754
3755 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003756 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003757 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003758
Vishnu Nair47074b82020-08-14 11:54:47 -07003759 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003761 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003762 mWindow->consumeFocusEvent(true);
3763 }
3764
Chris Ye2ad95392020-09-01 13:44:44 -07003765 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003766 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003767 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003768 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3769 mDispatcher->notifyKey(&keyArgs);
3770
3771 // Window should receive key down event.
3772 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3773 }
3774
3775 void expectKeyRepeatOnce(int32_t repeatCount) {
3776 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3777 InputEvent* repeatEvent = mWindow->consume();
3778 ASSERT_NE(nullptr, repeatEvent);
3779
3780 uint32_t eventType = repeatEvent->getType();
3781 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3782
3783 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3784 uint32_t eventAction = repeatKeyEvent->getAction();
3785 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3786 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3787 }
3788
Chris Ye2ad95392020-09-01 13:44:44 -07003789 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003790 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003791 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003792 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3793 mDispatcher->notifyKey(&keyArgs);
3794
3795 // Window should receive key down event.
3796 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3797 0 /*expectedFlags*/);
3798 }
3799};
3800
3801TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003802 sendAndConsumeKeyDown(1 /* deviceId */);
3803 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3804 expectKeyRepeatOnce(repeatCount);
3805 }
3806}
3807
3808TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3809 sendAndConsumeKeyDown(1 /* deviceId */);
3810 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3811 expectKeyRepeatOnce(repeatCount);
3812 }
3813 sendAndConsumeKeyDown(2 /* deviceId */);
3814 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003815 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3816 expectKeyRepeatOnce(repeatCount);
3817 }
3818}
3819
3820TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003821 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003822 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003823 sendAndConsumeKeyUp(1 /* deviceId */);
3824 mWindow->assertNoEvents();
3825}
3826
3827TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3828 sendAndConsumeKeyDown(1 /* deviceId */);
3829 expectKeyRepeatOnce(1 /*repeatCount*/);
3830 sendAndConsumeKeyDown(2 /* deviceId */);
3831 expectKeyRepeatOnce(1 /*repeatCount*/);
3832 // Stale key up from device 1.
3833 sendAndConsumeKeyUp(1 /* deviceId */);
3834 // Device 2 is still down, keep repeating
3835 expectKeyRepeatOnce(2 /*repeatCount*/);
3836 expectKeyRepeatOnce(3 /*repeatCount*/);
3837 // Device 2 key up
3838 sendAndConsumeKeyUp(2 /* deviceId */);
3839 mWindow->assertNoEvents();
3840}
3841
3842TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3843 sendAndConsumeKeyDown(1 /* deviceId */);
3844 expectKeyRepeatOnce(1 /*repeatCount*/);
3845 sendAndConsumeKeyDown(2 /* deviceId */);
3846 expectKeyRepeatOnce(1 /*repeatCount*/);
3847 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3848 sendAndConsumeKeyUp(2 /* deviceId */);
3849 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003850 mWindow->assertNoEvents();
3851}
3852
liushenxiang42232912021-05-21 20:24:09 +08003853TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3854 sendAndConsumeKeyDown(DEVICE_ID);
3855 expectKeyRepeatOnce(1 /*repeatCount*/);
3856 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3857 mDispatcher->notifyDeviceReset(&args);
3858 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3859 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3860 mWindow->assertNoEvents();
3861}
3862
Garfield Tan1c7bc862020-01-28 13:24:04 -08003863TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003864 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003865 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3866 InputEvent* repeatEvent = mWindow->consume();
3867 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3868 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3869 IdGenerator::getSource(repeatEvent->getId()));
3870 }
3871}
3872
3873TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003874 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003875
3876 std::unordered_set<int32_t> idSet;
3877 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3878 InputEvent* repeatEvent = mWindow->consume();
3879 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3880 int32_t id = repeatEvent->getId();
3881 EXPECT_EQ(idSet.end(), idSet.find(id));
3882 idSet.insert(id);
3883 }
3884}
3885
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003886/* Test InputDispatcher for MultiDisplay */
3887class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3888public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003889 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003890 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003891
Chris Yea209fde2020-07-22 13:54:51 -07003892 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003893 windowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003894 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003895
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003896 // Set focus window for primary display, but focused display would be second one.
3897 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003898 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003900 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003901 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003902
Chris Yea209fde2020-07-22 13:54:51 -07003903 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003904 windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07003905 sp<FakeWindowHandle>::make(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003906 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003907 // Set focus display to second one.
3908 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3909 // Set focus window for second display.
3910 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003911 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003912 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003913 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003914 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003915 }
3916
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003917 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003918 InputDispatcherTest::TearDown();
3919
Chris Yea209fde2020-07-22 13:54:51 -07003920 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003921 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003922 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003923 windowInSecondary.clear();
3924 }
3925
3926protected:
Chris Yea209fde2020-07-22 13:54:51 -07003927 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003928 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003929 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003930 sp<FakeWindowHandle> windowInSecondary;
3931};
3932
3933TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3934 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003938 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003939 windowInSecondary->assertNoEvents();
3940
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003941 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3943 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003945 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003946 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003947}
3948
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003949TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003950 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3952 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003953 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003954 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003955 windowInSecondary->assertNoEvents();
3956
3957 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003959 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003960 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003961 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003962
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003963 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003964 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003965
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003966 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003967 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3968 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003969
3970 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003971 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003972 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003973 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003974 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003975 windowInSecondary->assertNoEvents();
3976}
3977
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003978// Test per-display input monitors for motion event.
3979TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003980 FakeMonitorReceiver monitorInPrimary =
3981 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3982 FakeMonitorReceiver monitorInSecondary =
3983 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003984
3985 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3987 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003989 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003990 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003991 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003992 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003993
3994 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3996 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003998 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003999 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004000 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08004001 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004002
4003 // Test inject a non-pointer motion event.
4004 // If specific a display, it will dispatch to the focused window of particular display,
4005 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4007 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
4008 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004009 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004010 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004011 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004012 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004013}
4014
4015// Test per-display input monitors for key event.
4016TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004017 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08004018 FakeMonitorReceiver monitorInPrimary =
4019 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4020 FakeMonitorReceiver monitorInSecondary =
4021 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004022
4023 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
4025 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004026 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08004027 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08004028 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08004029 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08004030}
4031
Vishnu Nair958da932020-08-21 17:12:37 -07004032TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
4033 sp<FakeWindowHandle> secondWindowInPrimary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004034 sp<FakeWindowHandle>::make(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
Vishnu Nair958da932020-08-21 17:12:37 -07004035 secondWindowInPrimary->setFocusable(true);
4036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
4037 setFocusedWindow(secondWindowInPrimary);
4038 windowInPrimary->consumeFocusEvent(false);
4039 secondWindowInPrimary->consumeFocusEvent(true);
4040
4041 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
4043 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07004044 windowInPrimary->assertNoEvents();
4045 windowInSecondary->assertNoEvents();
4046 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4047}
4048
Arthur Hungdfd528e2021-12-08 13:23:04 +00004049TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
4050 FakeMonitorReceiver monitorInPrimary =
4051 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4052 FakeMonitorReceiver monitorInSecondary =
4053 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
4054
4055 // Test touch down on primary display.
4056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
4058 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4059 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4060 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4061
4062 // Test touch down on second display.
4063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4064 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
4065 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4066 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
4067 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
4068
4069 // Trigger cancel touch.
4070 mDispatcher->cancelCurrentTouch();
4071 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4072 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4073 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
4074 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
4075
4076 // Test inject a move motion event, no window/monitor should receive the event.
4077 ASSERT_EQ(InputEventInjectionResult::FAILED,
4078 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4079 ADISPLAY_ID_DEFAULT, {110, 200}))
4080 << "Inject motion event should return InputEventInjectionResult::FAILED";
4081 windowInPrimary->assertNoEvents();
4082 monitorInPrimary.assertNoEvents();
4083
4084 ASSERT_EQ(InputEventInjectionResult::FAILED,
4085 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
4086 SECOND_DISPLAY_ID, {110, 200}))
4087 << "Inject motion event should return InputEventInjectionResult::FAILED";
4088 windowInSecondary->assertNoEvents();
4089 monitorInSecondary.assertNoEvents();
4090}
4091
Jackal Guof9696682018-10-05 12:23:23 +08004092class InputFilterTest : public InputDispatcherTest {
4093protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004094 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
4095 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08004096 NotifyMotionArgs motionArgs;
4097
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004098 motionArgs =
4099 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004100 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004101 motionArgs =
4102 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08004103 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004104 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004105 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004106 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
4107 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08004108 } else {
4109 mFakePolicy->assertFilterInputEventWasNotCalled();
4110 }
4111 }
4112
4113 void testNotifyKey(bool expectToBeFiltered) {
4114 NotifyKeyArgs keyArgs;
4115
4116 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
4117 mDispatcher->notifyKey(&keyArgs);
4118 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
4119 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004120 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08004121
4122 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08004123 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08004124 } else {
4125 mFakePolicy->assertFilterInputEventWasNotCalled();
4126 }
4127 }
4128};
4129
4130// Test InputFilter for MotionEvent
4131TEST_F(InputFilterTest, MotionEvent_InputFilter) {
4132 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
4133 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4134 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4135
4136 // Enable InputFilter
4137 mDispatcher->setInputFilterEnabled(true);
4138 // Test touch on both primary and second display, and check if both events are filtered.
4139 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
4140 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
4141
4142 // Disable InputFilter
4143 mDispatcher->setInputFilterEnabled(false);
4144 // Test touch on both primary and second display, and check if both events aren't filtered.
4145 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
4146 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
4147}
4148
4149// Test InputFilter for KeyEvent
4150TEST_F(InputFilterTest, KeyEvent_InputFilter) {
4151 // Since the InputFilter is disabled by default, check if key event aren't filtered.
4152 testNotifyKey(/*expectToBeFiltered*/ false);
4153
4154 // Enable InputFilter
4155 mDispatcher->setInputFilterEnabled(true);
4156 // Send a key event, and check if it is filtered.
4157 testNotifyKey(/*expectToBeFiltered*/ true);
4158
4159 // Disable InputFilter
4160 mDispatcher->setInputFilterEnabled(false);
4161 // Send a key event, and check if it isn't filtered.
4162 testNotifyKey(/*expectToBeFiltered*/ false);
4163}
4164
Prabir Pradhan81420cc2021-09-06 10:28:50 -07004165// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
4166// logical display coordinate space.
4167TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
4168 ui::Transform firstDisplayTransform;
4169 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4170 ui::Transform secondDisplayTransform;
4171 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4172
4173 std::vector<gui::DisplayInfo> displayInfos(2);
4174 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4175 displayInfos[0].transform = firstDisplayTransform;
4176 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4177 displayInfos[1].transform = secondDisplayTransform;
4178
4179 mDispatcher->onWindowInfosChanged({}, displayInfos);
4180
4181 // Enable InputFilter
4182 mDispatcher->setInputFilterEnabled(true);
4183
4184 // Ensure the correct transforms are used for the displays.
4185 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4186 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4187}
4188
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004189class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4190protected:
4191 virtual void SetUp() override {
4192 InputDispatcherTest::SetUp();
4193
4194 /**
4195 * We don't need to enable input filter to test the injected event policy, but we enabled it
4196 * here to make the tests more realistic, since this policy only matters when inputfilter is
4197 * on.
4198 */
4199 mDispatcher->setInputFilterEnabled(true);
4200
4201 std::shared_ptr<InputApplicationHandle> application =
4202 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004203 mWindow = sp<FakeWindowHandle>::make(application, mDispatcher, "Test Window",
4204 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004205
4206 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4207 mWindow->setFocusable(true);
4208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4209 setFocusedWindow(mWindow);
4210 mWindow->consumeFocusEvent(true);
4211 }
4212
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004213 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4214 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004215 KeyEvent event;
4216
4217 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4218 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4219 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4220 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4221 const int32_t additionalPolicyFlags =
4222 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004224 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004225 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4226 policyFlags | additionalPolicyFlags));
4227
4228 InputEvent* received = mWindow->consume();
4229 ASSERT_NE(nullptr, received);
4230 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004231 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4232 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4233 ASSERT_EQ(flags, keyEvent.getFlags());
4234 }
4235
4236 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4237 int32_t flags) {
4238 MotionEvent event;
4239 PointerProperties pointerProperties[1];
4240 PointerCoords pointerCoords[1];
4241 pointerProperties[0].clear();
4242 pointerProperties[0].id = 0;
4243 pointerCoords[0].clear();
4244 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4245 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4246
4247 ui::Transform identityTransform;
4248 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4249 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4250 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4251 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4252 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004253 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004254 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004255 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4256
4257 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan5735a322022-04-11 17:23:34 +00004259 mDispatcher->injectInputEvent(&event, {} /*targetUid*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004260 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4261 policyFlags | additionalPolicyFlags));
4262
4263 InputEvent* received = mWindow->consume();
4264 ASSERT_NE(nullptr, received);
4265 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4266 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4267 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4268 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004269 }
4270
4271private:
4272 sp<FakeWindowHandle> mWindow;
4273};
4274
4275TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004276 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4277 // filter. Without it, the event will no different from a regularly injected event, and the
4278 // injected device id will be overwritten.
4279 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4280 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004281}
4282
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004283TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004284 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004285 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4286 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4287}
4288
4289TEST_F(InputFilterInjectionPolicyTest,
4290 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4291 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4292 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4293 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004294}
4295
4296TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4297 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004298 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004299}
4300
chaviwfd6d3512019-03-25 13:23:49 -07004301class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004302 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004303 InputDispatcherTest::SetUp();
4304
Chris Yea209fde2020-07-22 13:54:51 -07004305 std::shared_ptr<FakeApplicationHandle> application =
4306 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004307 mUnfocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004308 sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004309 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004310
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004311 mFocusedWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004312 sp<FakeWindowHandle>::make(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004313 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004314
4315 // Set focused application.
4316 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004317 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004318
4319 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004321 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004322 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004323 }
4324
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004325 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004326 InputDispatcherTest::TearDown();
4327
4328 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004329 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004330 }
4331
4332protected:
4333 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004334 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004335 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004336};
4337
4338// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4339// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4340// the onPointerDownOutsideFocus callback.
4341TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004343 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4344 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004345 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004346 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004347
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004348 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004349 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4350}
4351
4352// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4353// DOWN on the window that doesn't have focus. Ensure no window received the
4354// onPointerDownOutsideFocus callback.
4355TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004357 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004358 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004359 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004360
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004361 ASSERT_TRUE(mDispatcher->waitForIdle());
4362 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004363}
4364
4365// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4366// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4367TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4369 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004370 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004371 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004372
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004373 ASSERT_TRUE(mDispatcher->waitForIdle());
4374 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004375}
4376
4377// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4378// DOWN on the window that already has focus. Ensure no window received the
4379// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004380TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004382 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004383 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004385 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004386
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004387 ASSERT_TRUE(mDispatcher->waitForIdle());
4388 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004389}
4390
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004391// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4392// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4393TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4394 const MotionEvent event =
4395 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4396 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4397 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4398 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4399 .build();
4400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4401 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4402 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4403
4404 ASSERT_TRUE(mDispatcher->waitForIdle());
4405 mFakePolicy->assertOnPointerDownWasNotCalled();
4406 // Ensure that the unfocused window did not receive any FOCUS events.
4407 mUnfocusedWindow->assertNoEvents();
4408}
4409
chaviwaf87b3e2019-10-01 16:59:28 -07004410// These tests ensures we can send touch events to a single client when there are multiple input
4411// windows that point to the same client token.
4412class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4413 virtual void SetUp() override {
4414 InputDispatcherTest::SetUp();
4415
Chris Yea209fde2020-07-22 13:54:51 -07004416 std::shared_ptr<FakeApplicationHandle> application =
4417 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004418 mWindow1 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 1",
4419 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004420 mWindow1->setFrame(Rect(0, 0, 100, 100));
4421
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004422 mWindow2 = sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window 2",
4423 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004424 mWindow2->setFrame(Rect(100, 100, 200, 200));
4425
Arthur Hung72d8dc32020-03-28 00:48:39 +00004426 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004427 }
4428
4429protected:
4430 sp<FakeWindowHandle> mWindow1;
4431 sp<FakeWindowHandle> mWindow2;
4432
4433 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004434 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004435 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4436 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004437 }
4438
4439 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4440 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004441 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004442 InputEvent* event = window->consume();
4443
4444 ASSERT_NE(nullptr, event) << name.c_str()
4445 << ": consumer should have returned non-NULL event.";
4446
4447 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4448 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4449 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4450
4451 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004452 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004453
4454 for (size_t i = 0; i < points.size(); i++) {
4455 float expectedX = points[i].x;
4456 float expectedY = points[i].y;
4457
4458 EXPECT_EQ(expectedX, motionEvent.getX(i))
4459 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4460 << ", got " << motionEvent.getX(i);
4461 EXPECT_EQ(expectedY, motionEvent.getY(i))
4462 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4463 << ", got " << motionEvent.getY(i);
4464 }
4465 }
chaviw9eaa22c2020-07-01 16:21:27 -07004466
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004467 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004468 std::vector<PointF> expectedPoints) {
4469 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4470 ADISPLAY_ID_DEFAULT, touchedPoints);
4471 mDispatcher->notifyMotion(&motionArgs);
4472
4473 // Always consume from window1 since it's the window that has the InputReceiver
4474 consumeMotionEvent(mWindow1, action, expectedPoints);
4475 }
chaviwaf87b3e2019-10-01 16:59:28 -07004476};
4477
4478TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4479 // Touch Window 1
4480 PointF touchedPoint = {10, 10};
4481 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004482 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004483
4484 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004485 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004486
4487 // Touch Window 2
4488 touchedPoint = {150, 150};
4489 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004490 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004491}
4492
chaviw9eaa22c2020-07-01 16:21:27 -07004493TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4494 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004495 mWindow2->setWindowScale(0.5f, 0.5f);
4496
4497 // Touch Window 1
4498 PointF touchedPoint = {10, 10};
4499 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004500 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004501 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004502 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004503
4504 // Touch Window 2
4505 touchedPoint = {150, 150};
4506 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004507 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4508 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004509
chaviw9eaa22c2020-07-01 16:21:27 -07004510 // Update the transform so rotation is set
4511 mWindow2->setWindowTransform(0, -1, 1, 0);
4512 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4513 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004514}
4515
chaviw9eaa22c2020-07-01 16:21:27 -07004516TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004517 mWindow2->setWindowScale(0.5f, 0.5f);
4518
4519 // Touch Window 1
4520 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4521 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004522 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004523
4524 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004525 touchedPoints.push_back(PointF{150, 150});
4526 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004527 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004528
chaviw9eaa22c2020-07-01 16:21:27 -07004529 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004530 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004531 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004532
chaviw9eaa22c2020-07-01 16:21:27 -07004533 // Update the transform so rotation is set for Window 2
4534 mWindow2->setWindowTransform(0, -1, 1, 0);
4535 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004536 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004537}
4538
chaviw9eaa22c2020-07-01 16:21:27 -07004539TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004540 mWindow2->setWindowScale(0.5f, 0.5f);
4541
4542 // Touch Window 1
4543 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4544 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004545 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004546
4547 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004548 touchedPoints.push_back(PointF{150, 150});
4549 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004550
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004551 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004552
4553 // Move both windows
4554 touchedPoints = {{20, 20}, {175, 175}};
4555 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4556 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4557
chaviw9eaa22c2020-07-01 16:21:27 -07004558 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004559
chaviw9eaa22c2020-07-01 16:21:27 -07004560 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004561 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004562 expectedPoints.pop_back();
4563
4564 // Touch Window 2
4565 mWindow2->setWindowTransform(0, -1, 1, 0);
4566 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004567 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004568
4569 // Move both windows
4570 touchedPoints = {{20, 20}, {175, 175}};
4571 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4572 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4573
4574 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004575}
4576
4577TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4578 mWindow1->setWindowScale(0.5f, 0.5f);
4579
4580 // Touch Window 1
4581 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4582 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004583 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004584
4585 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004586 touchedPoints.push_back(PointF{150, 150});
4587 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004588
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004589 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004590
4591 // Move both windows
4592 touchedPoints = {{20, 20}, {175, 175}};
4593 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4594 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4595
chaviw9eaa22c2020-07-01 16:21:27 -07004596 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004597}
4598
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004599class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4600 virtual void SetUp() override {
4601 InputDispatcherTest::SetUp();
4602
Chris Yea209fde2020-07-22 13:54:51 -07004603 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004604 mApplication->setDispatchingTimeout(20ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004605 mWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "TestWindow",
4606 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004607 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004608 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004609 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004610
4611 // Set focused application.
4612 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4613
4614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004615 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004616 mWindow->consumeFocusEvent(true);
4617 }
4618
4619 virtual void TearDown() override {
4620 InputDispatcherTest::TearDown();
4621 mWindow.clear();
4622 }
4623
4624protected:
Chris Yea209fde2020-07-22 13:54:51 -07004625 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004626 sp<FakeWindowHandle> mWindow;
4627 static constexpr PointF WINDOW_LOCATION = {20, 20};
4628
4629 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004631 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4632 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004634 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4635 WINDOW_LOCATION));
4636 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004637
4638 sp<FakeWindowHandle> addSpyWindow() {
4639 sp<FakeWindowHandle> spy =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07004640 sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004641 spy->setTrustedOverlay(true);
4642 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004643 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004644 spy->setDispatchingTimeout(30ms);
4645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4646 return spy;
4647 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004648};
4649
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650// Send a tap and respond, which should not cause an ANR.
4651TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4652 tapOnWindow();
4653 mWindow->consumeMotionDown();
4654 mWindow->consumeMotionUp();
4655 ASSERT_TRUE(mDispatcher->waitForIdle());
4656 mFakePolicy->assertNotifyAnrWasNotCalled();
4657}
4658
4659// Send a regular key and respond, which should not cause an ANR.
4660TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004662 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4663 ASSERT_TRUE(mDispatcher->waitForIdle());
4664 mFakePolicy->assertNotifyAnrWasNotCalled();
4665}
4666
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004667TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4668 mWindow->setFocusable(false);
4669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4670 mWindow->consumeFocusEvent(false);
4671
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004672 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004673 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004674 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4675 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004676 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004677 // Key will not go to window because we have no focused window.
4678 // The 'no focused window' ANR timer should start instead.
4679
4680 // Now, the focused application goes away.
4681 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4682 // The key should get dropped and there should be no ANR.
4683
4684 ASSERT_TRUE(mDispatcher->waitForIdle());
4685 mFakePolicy->assertNotifyAnrWasNotCalled();
4686}
4687
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004688// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4690// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004691TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4694 WINDOW_LOCATION));
4695
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004696 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4697 ASSERT_TRUE(sequenceNum);
4698 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004699 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004701 mWindow->finishEvent(*sequenceNum);
4702 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4703 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004704 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004705 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004706}
4707
4708// Send a key to the app and have the app not respond right away.
4709TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4710 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004712 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4713 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004714 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004715 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004716 ASSERT_TRUE(mDispatcher->waitForIdle());
4717}
4718
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004719// We have a focused application, but no focused window
4720TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004721 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4723 mWindow->consumeFocusEvent(false);
4724
4725 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4728 WINDOW_LOCATION));
4729 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4730 mDispatcher->waitForIdle();
4731 mFakePolicy->assertNotifyAnrWasNotCalled();
4732
4733 // Once a focused event arrives, we get an ANR for this application
4734 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4735 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004736 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004737 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004738 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004739 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004741 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 ASSERT_TRUE(mDispatcher->waitForIdle());
4743}
4744
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004745/**
4746 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4747 * there will not be an ANR.
4748 */
4749TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4750 mWindow->setFocusable(false);
4751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4752 mWindow->consumeFocusEvent(false);
4753
4754 KeyEvent event;
4755 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4756 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4757
4758 // Define a valid key down event that is stale (too old).
4759 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4760 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4761 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4762
4763 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4764
4765 InputEventInjectionResult result =
Prabir Pradhan5735a322022-04-11 17:23:34 +00004766 mDispatcher->injectInputEvent(&event, {} /* targetUid */,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004767 InputEventInjectionSync::WAIT_FOR_RESULT,
4768 INJECT_EVENT_TIMEOUT, policyFlags);
4769 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4770 << "Injection should fail because the event is stale";
4771
4772 ASSERT_TRUE(mDispatcher->waitForIdle());
4773 mFakePolicy->assertNotifyAnrWasNotCalled();
4774 mWindow->assertNoEvents();
4775}
4776
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004778// Make sure that we don't notify policy twice about the same ANR.
4779TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004780 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4782 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004783
4784 // Once a focused event arrives, we get an ANR for this application
4785 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4786 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004787 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004789 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004790 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 const std::chrono::duration appTimeout =
4792 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004793 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004795 std::this_thread::sleep_for(appTimeout);
4796 // ANR should not be raised again. It is up to policy to do that if it desires.
4797 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004799 // If we now get a focused window, the ANR should stop, but the policy handles that via
4800 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801 ASSERT_TRUE(mDispatcher->waitForIdle());
4802}
4803
4804// We have a focused application, but no focused window
4805TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004806 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4808 mWindow->consumeFocusEvent(false);
4809
4810 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004811 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4814 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004815
4816 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004817 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818
4819 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 ASSERT_TRUE(mDispatcher->waitForIdle());
4822 mWindow->assertNoEvents();
4823}
4824
4825/**
4826 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4827 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4828 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4829 * the ANR mechanism should still work.
4830 *
4831 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4832 * DOWN event, while not responding on the second one.
4833 */
4834TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4835 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4836 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4837 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4838 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4839 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004840 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841
4842 // Now send ACTION_UP, with identical timestamp
4843 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4844 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4845 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4846 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848
4849 // We have now sent down and up. Let's consume first event and then ANR on the second.
4850 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4851 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004852 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853}
4854
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004855// A spy window can receive an ANR
4856TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4857 sp<FakeWindowHandle> spy = addSpyWindow();
4858
4859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4860 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4861 WINDOW_LOCATION));
4862 mWindow->consumeMotionDown();
4863
4864 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4865 ASSERT_TRUE(sequenceNum);
4866 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004867 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004868
4869 spy->finishEvent(*sequenceNum);
4870 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4871 0 /*flags*/);
4872 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004873 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004874}
4875
4876// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004878TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4879 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004880
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4882 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004884 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004885
4886 // Stuck on the ACTION_UP
4887 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004888 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004890 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004892 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4893 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894
4895 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4896 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004897 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004899 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004900}
4901
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004902// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004904TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4905 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906
4907 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004908 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4909 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004910
4911 mWindow->consumeMotionDown();
4912 // Stuck on the ACTION_UP
4913 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004914 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004915
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004916 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004917 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004918 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4919 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4922 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004923 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004925 spy->assertNoEvents();
4926}
4927
4928TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4929 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4930
4931 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4932
4933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4934 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4935 WINDOW_LOCATION));
4936
4937 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4938 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4939 ASSERT_TRUE(consumeSeq);
4940
Prabir Pradhanedd96402022-02-15 01:46:16 -08004941 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004942
4943 monitor.finishEvent(*consumeSeq);
4944 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4945
4946 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004947 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948}
4949
4950// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4951// process events, you don't get an anr. When the window later becomes unresponsive again, you
4952// get an ANR again.
4953// 1. tap -> block on ACTION_UP -> receive ANR
4954// 2. consume all pending events (= queue becomes healthy again)
4955// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4956TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4957 tapOnWindow();
4958
4959 mWindow->consumeMotionDown();
4960 // Block on ACTION_UP
4961 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004962 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4964 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004965 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004966 mWindow->assertNoEvents();
4967
4968 tapOnWindow();
4969 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004970 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971 mWindow->consumeMotionUp();
4972
4973 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004974 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004975 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976 mWindow->assertNoEvents();
4977}
4978
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004979// If a connection remains unresponsive for a while, make sure policy is only notified once about
4980// it.
4981TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4984 WINDOW_LOCATION));
4985
4986 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004987 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004989 // 'notifyConnectionUnresponsive' should only be called once per connection
4990 mFakePolicy->assertNotifyAnrWasNotCalled();
4991 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004992 mWindow->consumeMotionDown();
4993 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4994 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4995 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004996 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004997 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004998 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999}
5000
5001/**
5002 * If a window is processing a motion event, and then a key event comes in, the key event should
5003 * not to to the focused window until the motion is processed.
5004 *
5005 * Warning!!!
5006 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5007 * and the injection timeout that we specify when injecting the key.
5008 * We must have the injection timeout (10ms) be smaller than
5009 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5010 *
5011 * If that value changes, this test should also change.
5012 */
5013TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
5014 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5015 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5016
5017 tapOnWindow();
5018 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5019 ASSERT_TRUE(downSequenceNum);
5020 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5021 ASSERT_TRUE(upSequenceNum);
5022 // Don't finish the events yet, and send a key
5023 // Injection will "succeed" because we will eventually give up and send the key to the focused
5024 // window even if motions are still being processed. But because the injection timeout is short,
5025 // we will receive INJECTION_TIMED_OUT as the result.
5026
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005027 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005029 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
5030 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031 // Key will not be sent to the window, yet, because the window is still processing events
5032 // and the key remains pending, waiting for the touch events to be processed
5033 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5034 ASSERT_FALSE(keySequenceNum);
5035
5036 std::this_thread::sleep_for(500ms);
5037 // if we wait long enough though, dispatcher will give up, and still send the key
5038 // to the focused window, even though we have not yet finished the motion event
5039 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5040 mWindow->finishEvent(*downSequenceNum);
5041 mWindow->finishEvent(*upSequenceNum);
5042}
5043
5044/**
5045 * If a window is processing a motion event, and then a key event comes in, the key event should
5046 * not go to the focused window until the motion is processed.
5047 * If then a new motion comes in, then the pending key event should be going to the currently
5048 * focused window right away.
5049 */
5050TEST_F(InputDispatcherSingleWindowAnr,
5051 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
5052 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
5053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
5054
5055 tapOnWindow();
5056 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
5057 ASSERT_TRUE(downSequenceNum);
5058 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
5059 ASSERT_TRUE(upSequenceNum);
5060 // Don't finish the events yet, and send a key
5061 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005063 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005064 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005065 // At this point, key is still pending, and should not be sent to the application yet.
5066 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
5067 ASSERT_FALSE(keySequenceNum);
5068
5069 // Now tap down again. It should cause the pending key to go to the focused window right away.
5070 tapOnWindow();
5071 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
5072 // the other events yet. We can finish events in any order.
5073 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
5074 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
5075 mWindow->consumeMotionDown();
5076 mWindow->consumeMotionUp();
5077 mWindow->assertNoEvents();
5078}
5079
5080class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
5081 virtual void SetUp() override {
5082 InputDispatcherTest::SetUp();
5083
Chris Yea209fde2020-07-22 13:54:51 -07005084 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 mApplication->setDispatchingTimeout(10ms);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005086 mUnfocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Unfocused",
5087 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005089 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005090 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005092 mFocusedWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Focused",
5093 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05005094 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005095 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005096
5097 // Set focused application.
5098 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07005099 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100
5101 // Expect one focus window exist in display.
5102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005103 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005104 mFocusedWindow->consumeFocusEvent(true);
5105 }
5106
5107 virtual void TearDown() override {
5108 InputDispatcherTest::TearDown();
5109
5110 mUnfocusedWindow.clear();
5111 mFocusedWindow.clear();
5112 }
5113
5114protected:
Chris Yea209fde2020-07-22 13:54:51 -07005115 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116 sp<FakeWindowHandle> mUnfocusedWindow;
5117 sp<FakeWindowHandle> mFocusedWindow;
5118 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
5119 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
5120 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
5121
5122 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
5123
5124 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
5125
5126private:
5127 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005129 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5130 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5133 location));
5134 }
5135};
5136
5137// If we have 2 windows that are both unresponsive, the one with the shortest timeout
5138// should be ANR'd first.
5139TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005141 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5142 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005143 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005144 mFocusedWindow->consumeMotionDown();
5145 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5146 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5147 // We consumed all events, so no ANR
5148 ASSERT_TRUE(mDispatcher->waitForIdle());
5149 mFakePolicy->assertNotifyAnrWasNotCalled();
5150
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005151 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5153 FOCUSED_WINDOW_LOCATION));
5154 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
5155 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005156
5157 const std::chrono::duration timeout =
5158 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005159 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005160 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
5161 // sequence to make it consistent
5162 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005163 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005164 mFocusedWindow->consumeMotionDown();
5165 // This cancel is generated because the connection was unresponsive
5166 mFocusedWindow->consumeMotionCancel();
5167 mFocusedWindow->assertNoEvents();
5168 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005169 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005170 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5171 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005172 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005173}
5174
5175// If we have 2 windows with identical timeouts that are both unresponsive,
5176// it doesn't matter which order they should have ANR.
5177// But we should receive ANR for both.
5178TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5179 // Set the timeout for unfocused window to match the focused window
5180 mUnfocusedWindow->setDispatchingTimeout(10ms);
5181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5182
5183 tapOnFocusedWindow();
5184 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005185 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5186 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5187 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005188
5189 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005190 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5191 mFocusedWindow->getToken() == anrConnectionToken2);
5192 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5193 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005194
5195 ASSERT_TRUE(mDispatcher->waitForIdle());
5196 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005197
5198 mFocusedWindow->consumeMotionDown();
5199 mFocusedWindow->consumeMotionUp();
5200 mUnfocusedWindow->consumeMotionOutside();
5201
Prabir Pradhanedd96402022-02-15 01:46:16 -08005202 sp<IBinder> responsiveToken1, responsiveToken2;
5203 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5204 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005205
5206 // Both applications should be marked as responsive, in any order
5207 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5208 mFocusedWindow->getToken() == responsiveToken2);
5209 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5210 mUnfocusedWindow->getToken() == responsiveToken2);
5211 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005212}
5213
5214// If a window is already not responding, the second tap on the same window should be ignored.
5215// We should also log an error to account for the dropped event (not tested here).
5216// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5217TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5218 tapOnFocusedWindow();
5219 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5220 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5221 // Receive the events, but don't respond
5222 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5223 ASSERT_TRUE(downEventSequenceNum);
5224 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5225 ASSERT_TRUE(upEventSequenceNum);
5226 const std::chrono::duration timeout =
5227 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005228 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005229
5230 // Tap once again
5231 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005233 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5234 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005235 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005236 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5237 FOCUSED_WINDOW_LOCATION));
5238 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5239 // valid touch target
5240 mUnfocusedWindow->assertNoEvents();
5241
5242 // Consume the first tap
5243 mFocusedWindow->finishEvent(*downEventSequenceNum);
5244 mFocusedWindow->finishEvent(*upEventSequenceNum);
5245 ASSERT_TRUE(mDispatcher->waitForIdle());
5246 // The second tap did not go to the focused window
5247 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005248 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005249 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5250 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005251 mFakePolicy->assertNotifyAnrWasNotCalled();
5252}
5253
5254// If you tap outside of all windows, there will not be ANR
5255TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005256 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005257 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5258 LOCATION_OUTSIDE_ALL_WINDOWS));
5259 ASSERT_TRUE(mDispatcher->waitForIdle());
5260 mFakePolicy->assertNotifyAnrWasNotCalled();
5261}
5262
5263// Since the focused window is paused, tapping on it should not produce any events
5264TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5265 mFocusedWindow->setPaused(true);
5266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5267
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005268 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005269 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5270 FOCUSED_WINDOW_LOCATION));
5271
5272 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5273 ASSERT_TRUE(mDispatcher->waitForIdle());
5274 // Should not ANR because the window is paused, and touches shouldn't go to it
5275 mFakePolicy->assertNotifyAnrWasNotCalled();
5276
5277 mFocusedWindow->assertNoEvents();
5278 mUnfocusedWindow->assertNoEvents();
5279}
5280
5281/**
5282 * If a window is processing a motion event, and then a key event comes in, the key event should
5283 * not to to the focused window until the motion is processed.
5284 * If a different window becomes focused at this time, the key should go to that window instead.
5285 *
5286 * Warning!!!
5287 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5288 * and the injection timeout that we specify when injecting the key.
5289 * We must have the injection timeout (10ms) be smaller than
5290 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5291 *
5292 * If that value changes, this test should also change.
5293 */
5294TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5295 // Set a long ANR timeout to prevent it from triggering
5296 mFocusedWindow->setDispatchingTimeout(2s);
5297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5298
5299 tapOnUnfocusedWindow();
5300 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5301 ASSERT_TRUE(downSequenceNum);
5302 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5303 ASSERT_TRUE(upSequenceNum);
5304 // Don't finish the events yet, and send a key
5305 // Injection will succeed because we will eventually give up and send the key to the focused
5306 // window even if motions are still being processed.
5307
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005308 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005309 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005310 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5311 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005312 // Key will not be sent to the window, yet, because the window is still processing events
5313 // and the key remains pending, waiting for the touch events to be processed
5314 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5315 ASSERT_FALSE(keySequenceNum);
5316
5317 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005318 mFocusedWindow->setFocusable(false);
5319 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005321 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005322
5323 // Focus events should precede the key events
5324 mUnfocusedWindow->consumeFocusEvent(true);
5325 mFocusedWindow->consumeFocusEvent(false);
5326
5327 // Finish the tap events, which should unblock dispatcher
5328 mUnfocusedWindow->finishEvent(*downSequenceNum);
5329 mUnfocusedWindow->finishEvent(*upSequenceNum);
5330
5331 // Now that all queues are cleared and no backlog in the connections, the key event
5332 // can finally go to the newly focused "mUnfocusedWindow".
5333 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5334 mFocusedWindow->assertNoEvents();
5335 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005336 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005337}
5338
5339// When the touch stream is split across 2 windows, and one of them does not respond,
5340// then ANR should be raised and the touch should be canceled for the unresponsive window.
5341// The other window should not be affected by that.
5342TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5343 // Touch Window 1
5344 NotifyMotionArgs motionArgs =
5345 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5346 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5347 mDispatcher->notifyMotion(&motionArgs);
5348 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5349 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5350
5351 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005352 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5353 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005354 mDispatcher->notifyMotion(&motionArgs);
5355
5356 const std::chrono::duration timeout =
5357 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005358 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005359
5360 mUnfocusedWindow->consumeMotionDown();
5361 mFocusedWindow->consumeMotionDown();
5362 // Focused window may or may not receive ACTION_MOVE
5363 // But it should definitely receive ACTION_CANCEL due to the ANR
5364 InputEvent* event;
5365 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5366 ASSERT_TRUE(moveOrCancelSequenceNum);
5367 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5368 ASSERT_NE(nullptr, event);
5369 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5370 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5371 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5372 mFocusedWindow->consumeMotionCancel();
5373 } else {
5374 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5375 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005376 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005377 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5378 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005379
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005380 mUnfocusedWindow->assertNoEvents();
5381 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005382 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005383}
5384
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005385/**
5386 * If we have no focused window, and a key comes in, we start the ANR timer.
5387 * The focused application should add a focused window before the timer runs out to prevent ANR.
5388 *
5389 * If the user touches another application during this time, the key should be dropped.
5390 * Next, if a new focused window comes in, without toggling the focused application,
5391 * then no ANR should occur.
5392 *
5393 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5394 * but in some cases the policy may not update the focused application.
5395 */
5396TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5397 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5398 std::make_shared<FakeApplicationHandle>();
5399 focusedApplication->setDispatchingTimeout(60ms);
5400 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5401 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5402 mFocusedWindow->setFocusable(false);
5403
5404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5405 mFocusedWindow->consumeFocusEvent(false);
5406
5407 // Send a key. The ANR timer should start because there is no focused window.
5408 // 'focusedApplication' will get blamed if this timer completes.
5409 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005410 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005411 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005412 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5413 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005415
5416 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5417 // then the injected touches won't cause the focused event to get dropped.
5418 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5419 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5420 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5421 // For this test, it means that the key would get delivered to the window once it becomes
5422 // focused.
5423 std::this_thread::sleep_for(10ms);
5424
5425 // Touch unfocused window. This should force the pending key to get dropped.
5426 NotifyMotionArgs motionArgs =
5427 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5428 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5429 mDispatcher->notifyMotion(&motionArgs);
5430
5431 // We do not consume the motion right away, because that would require dispatcher to first
5432 // process (== drop) the key event, and by that time, ANR will be raised.
5433 // Set the focused window first.
5434 mFocusedWindow->setFocusable(true);
5435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5436 setFocusedWindow(mFocusedWindow);
5437 mFocusedWindow->consumeFocusEvent(true);
5438 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5439 // to another application. This could be a bug / behaviour in the policy.
5440
5441 mUnfocusedWindow->consumeMotionDown();
5442
5443 ASSERT_TRUE(mDispatcher->waitForIdle());
5444 // Should not ANR because we actually have a focused window. It was just added too slowly.
5445 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5446}
5447
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005448// These tests ensure we cannot send touch events to a window that's positioned behind a window
5449// that has feature NO_INPUT_CHANNEL.
5450// Layout:
5451// Top (closest to user)
5452// mNoInputWindow (above all windows)
5453// mBottomWindow
5454// Bottom (furthest from user)
5455class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5456 virtual void SetUp() override {
5457 InputDispatcherTest::SetUp();
5458
5459 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005460 mNoInputWindow =
5461 sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5462 "Window without input channel", ADISPLAY_ID_DEFAULT,
5463 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005464
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005465 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005466 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5467 // It's perfectly valid for this window to not have an associated input channel
5468
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005469 mBottomWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher, "Bottom window",
5470 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005471 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5472
5473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5474 }
5475
5476protected:
5477 std::shared_ptr<FakeApplicationHandle> mApplication;
5478 sp<FakeWindowHandle> mNoInputWindow;
5479 sp<FakeWindowHandle> mBottomWindow;
5480};
5481
5482TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5483 PointF touchedPoint = {10, 10};
5484
5485 NotifyMotionArgs motionArgs =
5486 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5487 ADISPLAY_ID_DEFAULT, {touchedPoint});
5488 mDispatcher->notifyMotion(&motionArgs);
5489
5490 mNoInputWindow->assertNoEvents();
5491 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5492 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5493 // and therefore should prevent mBottomWindow from receiving touches
5494 mBottomWindow->assertNoEvents();
5495}
5496
5497/**
5498 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5499 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5500 */
5501TEST_F(InputDispatcherMultiWindowOcclusionTests,
5502 NoInputChannelFeature_DropsTouchesWithValidChannel) {
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005503 mNoInputWindow = sp<FakeWindowHandle>::make(mApplication, mDispatcher,
5504 "Window with input channel and NO_INPUT_CHANNEL",
5505 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005506
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005507 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005508 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5510
5511 PointF touchedPoint = {10, 10};
5512
5513 NotifyMotionArgs motionArgs =
5514 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5515 ADISPLAY_ID_DEFAULT, {touchedPoint});
5516 mDispatcher->notifyMotion(&motionArgs);
5517
5518 mNoInputWindow->assertNoEvents();
5519 mBottomWindow->assertNoEvents();
5520}
5521
Vishnu Nair958da932020-08-21 17:12:37 -07005522class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5523protected:
5524 std::shared_ptr<FakeApplicationHandle> mApp;
5525 sp<FakeWindowHandle> mWindow;
5526 sp<FakeWindowHandle> mMirror;
5527
5528 virtual void SetUp() override {
5529 InputDispatcherTest::SetUp();
5530 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005531 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5532 mMirror = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindowMirror",
5533 ADISPLAY_ID_DEFAULT, mWindow->getToken());
Vishnu Nair958da932020-08-21 17:12:37 -07005534 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5535 mWindow->setFocusable(true);
5536 mMirror->setFocusable(true);
5537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5538 }
5539};
5540
5541TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5542 // Request focus on a mirrored window
5543 setFocusedWindow(mMirror);
5544
5545 // window gets focused
5546 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5548 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005549 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5550}
5551
5552// A focused & mirrored window remains focused only if the window and its mirror are both
5553// focusable.
5554TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5555 setFocusedWindow(mMirror);
5556
5557 // window gets focused
5558 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005559 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5560 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005561 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5563 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005564 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5565
5566 mMirror->setFocusable(false);
5567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5568
5569 // window loses focus since one of the windows associated with the token in not focusable
5570 mWindow->consumeFocusEvent(false);
5571
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005572 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5573 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005574 mWindow->assertNoEvents();
5575}
5576
5577// A focused & mirrored window remains focused until the window and its mirror both become
5578// invisible.
5579TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5580 setFocusedWindow(mMirror);
5581
5582 // window gets focused
5583 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5585 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005586 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5588 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005589 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5590
5591 mMirror->setVisible(false);
5592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5593
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5595 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005596 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5598 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005599 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5600
5601 mWindow->setVisible(false);
5602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5603
5604 // window loses focus only after all windows associated with the token become invisible.
5605 mWindow->consumeFocusEvent(false);
5606
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005607 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5608 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005609 mWindow->assertNoEvents();
5610}
5611
5612// A focused & mirrored window remains focused until both windows are removed.
5613TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5614 setFocusedWindow(mMirror);
5615
5616 // window gets focused
5617 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5619 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005620 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5622 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005623 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5624
5625 // single window is removed but the window token remains focused
5626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5629 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005630 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5632 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005633 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5634
5635 // Both windows are removed
5636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5637 mWindow->consumeFocusEvent(false);
5638
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005639 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5640 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005641 mWindow->assertNoEvents();
5642}
5643
5644// Focus request can be pending until one window becomes visible.
5645TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5646 // Request focus on an invisible mirror.
5647 mWindow->setVisible(false);
5648 mMirror->setVisible(false);
5649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5650 setFocusedWindow(mMirror);
5651
5652 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005654 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005655 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005656
5657 mMirror->setVisible(true);
5658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5659
5660 // window gets focused
5661 mWindow->consumeFocusEvent(true);
5662 // window gets the pending key event
5663 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5664}
Prabir Pradhan99987712020-11-10 18:43:05 -08005665
5666class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5667protected:
5668 std::shared_ptr<FakeApplicationHandle> mApp;
5669 sp<FakeWindowHandle> mWindow;
5670 sp<FakeWindowHandle> mSecondWindow;
5671
5672 void SetUp() override {
5673 InputDispatcherTest::SetUp();
5674 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005675 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005676 mWindow->setFocusable(true);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005677 mSecondWindow =
5678 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Prabir Pradhan99987712020-11-10 18:43:05 -08005679 mSecondWindow->setFocusable(true);
5680
5681 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5683
5684 setFocusedWindow(mWindow);
5685 mWindow->consumeFocusEvent(true);
5686 }
5687
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005688 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5689 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005690 mDispatcher->notifyPointerCaptureChanged(&args);
5691 }
5692
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005693 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5694 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005695 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005696 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5697 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005698 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005699 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005700 }
5701};
5702
5703TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5704 // Ensure that capture cannot be obtained for unfocused windows.
5705 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5706 mFakePolicy->assertSetPointerCaptureNotCalled();
5707 mSecondWindow->assertNoEvents();
5708
5709 // Ensure that capture can be enabled from the focus window.
5710 requestAndVerifyPointerCapture(mWindow, true);
5711
5712 // Ensure that capture cannot be disabled from a window that does not have capture.
5713 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5714 mFakePolicy->assertSetPointerCaptureNotCalled();
5715
5716 // Ensure that capture can be disabled from the window with capture.
5717 requestAndVerifyPointerCapture(mWindow, false);
5718}
5719
5720TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005721 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005722
5723 setFocusedWindow(mSecondWindow);
5724
5725 // Ensure that the capture disabled event was sent first.
5726 mWindow->consumeCaptureEvent(false);
5727 mWindow->consumeFocusEvent(false);
5728 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005729 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005730
5731 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005732 notifyPointerCaptureChanged({});
5733 notifyPointerCaptureChanged(request);
5734 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005735 mWindow->assertNoEvents();
5736 mSecondWindow->assertNoEvents();
5737 mFakePolicy->assertSetPointerCaptureNotCalled();
5738}
5739
5740TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005741 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005742
5743 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005744 notifyPointerCaptureChanged({});
5745 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005746
5747 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005748 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005749 mWindow->consumeCaptureEvent(false);
5750 mWindow->assertNoEvents();
5751}
5752
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005753TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5754 requestAndVerifyPointerCapture(mWindow, true);
5755
5756 // The first window loses focus.
5757 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005758 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005759 mWindow->consumeCaptureEvent(false);
5760
5761 // Request Pointer Capture from the second window before the notification from InputReader
5762 // arrives.
5763 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005764 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005765
5766 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005767 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005768
5769 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005770 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005771
5772 mSecondWindow->consumeFocusEvent(true);
5773 mSecondWindow->consumeCaptureEvent(true);
5774}
5775
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005776TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5777 // App repeatedly enables and disables capture.
5778 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5779 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5780 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5781 mFakePolicy->assertSetPointerCaptureCalled(false);
5782 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5783 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5784
5785 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5786 // first request is now stale, this should do nothing.
5787 notifyPointerCaptureChanged(firstRequest);
5788 mWindow->assertNoEvents();
5789
5790 // InputReader notifies that the second request was enabled.
5791 notifyPointerCaptureChanged(secondRequest);
5792 mWindow->consumeCaptureEvent(true);
5793}
5794
Prabir Pradhan7092e262022-05-03 16:51:09 +00005795TEST_F(InputDispatcherPointerCaptureTests, RapidToggleRequests) {
5796 requestAndVerifyPointerCapture(mWindow, true);
5797
5798 // App toggles pointer capture off and on.
5799 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5800 mFakePolicy->assertSetPointerCaptureCalled(false);
5801
5802 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5803 auto enableRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5804
5805 // InputReader notifies that the latest "enable" request was processed, while skipping over the
5806 // preceding "disable" request.
5807 notifyPointerCaptureChanged(enableRequest);
5808
5809 // Since pointer capture was never disabled during the rapid toggle, the window does not receive
5810 // any notifications.
5811 mWindow->assertNoEvents();
5812}
5813
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005814class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5815protected:
5816 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005817
5818 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5819 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5820
5821 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5822 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5823
5824 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5825 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5826 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5827 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5828 MAXIMUM_OBSCURING_OPACITY);
5829
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005830 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005831 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005832 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005833
5834 sp<FakeWindowHandle> mTouchWindow;
5835
5836 virtual void SetUp() override {
5837 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005838 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005839 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5840 }
5841
5842 virtual void TearDown() override {
5843 InputDispatcherTest::TearDown();
5844 mTouchWindow.clear();
5845 }
5846
chaviw3277faf2021-05-19 16:45:23 -05005847 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5848 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005849 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005850 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005851 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005852 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005853 return window;
5854 }
5855
5856 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5857 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5858 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07005859 sp<FakeWindowHandle>::make(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005860 // Generate an arbitrary PID based on the UID
5861 window->setOwnerInfo(1777 + (uid % 10000), uid);
5862 return window;
5863 }
5864
5865 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5866 NotifyMotionArgs args =
5867 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5868 ADISPLAY_ID_DEFAULT, points);
5869 mDispatcher->notifyMotion(&args);
5870 }
5871};
5872
5873TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005874 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005875 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005877
5878 touch();
5879
5880 mTouchWindow->assertNoEvents();
5881}
5882
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005883TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005884 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5885 const sp<FakeWindowHandle>& w =
5886 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5888
5889 touch();
5890
5891 mTouchWindow->assertNoEvents();
5892}
5893
5894TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005895 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5896 const sp<FakeWindowHandle>& w =
5897 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5899
5900 touch();
5901
5902 w->assertNoEvents();
5903}
5904
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005905TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005906 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005908
5909 touch();
5910
5911 mTouchWindow->consumeAnyMotionDown();
5912}
5913
5914TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005915 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005916 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005917 w->setFrame(Rect(0, 0, 50, 50));
5918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005919
5920 touch({PointF{100, 100}});
5921
5922 mTouchWindow->consumeAnyMotionDown();
5923}
5924
5925TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005926 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005927 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005928 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5929
5930 touch();
5931
5932 mTouchWindow->consumeAnyMotionDown();
5933}
5934
5935TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5936 const sp<FakeWindowHandle>& w =
5937 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005939
5940 touch();
5941
5942 mTouchWindow->consumeAnyMotionDown();
5943}
5944
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005945TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5946 const sp<FakeWindowHandle>& w =
5947 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5948 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5949
5950 touch();
5951
5952 w->assertNoEvents();
5953}
5954
5955/**
5956 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5957 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5958 * window, the occluding window will still receive ACTION_OUTSIDE event.
5959 */
5960TEST_F(InputDispatcherUntrustedTouchesTest,
5961 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5962 const sp<FakeWindowHandle>& w =
5963 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005964 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5966
5967 touch();
5968
5969 w->consumeMotionOutside();
5970}
5971
5972TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5973 const sp<FakeWindowHandle>& w =
5974 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005975 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5977
5978 touch();
5979
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005980 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005981}
5982
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005983TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005984 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005985 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5986 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005987 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5988
5989 touch();
5990
5991 mTouchWindow->consumeAnyMotionDown();
5992}
5993
5994TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5995 const sp<FakeWindowHandle>& w =
5996 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5997 MAXIMUM_OBSCURING_OPACITY);
5998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005999
6000 touch();
6001
6002 mTouchWindow->consumeAnyMotionDown();
6003}
6004
6005TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006006 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006007 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6008 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006009 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6010
6011 touch();
6012
6013 mTouchWindow->assertNoEvents();
6014}
6015
6016TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
6017 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
6018 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006019 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6020 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006021 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006022 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6023 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6025
6026 touch();
6027
6028 mTouchWindow->assertNoEvents();
6029}
6030
6031TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
6032 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
6033 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006034 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
6035 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006036 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006037 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
6038 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6040
6041 touch();
6042
6043 mTouchWindow->consumeAnyMotionDown();
6044}
6045
6046TEST_F(InputDispatcherUntrustedTouchesTest,
6047 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
6048 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006049 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6050 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006051 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006052 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6053 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6055
6056 touch();
6057
6058 mTouchWindow->consumeAnyMotionDown();
6059}
6060
6061TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
6062 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006063 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6064 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006065 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006066 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6067 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00006068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00006069
6070 touch();
6071
6072 mTouchWindow->assertNoEvents();
6073}
6074
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006075TEST_F(InputDispatcherUntrustedTouchesTest,
6076 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
6077 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006078 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6079 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006080 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006081 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6082 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6084
6085 touch();
6086
6087 mTouchWindow->assertNoEvents();
6088}
6089
6090TEST_F(InputDispatcherUntrustedTouchesTest,
6091 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
6092 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006093 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6094 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006095 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006096 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6097 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006098 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
6099
6100 touch();
6101
6102 mTouchWindow->consumeAnyMotionDown();
6103}
6104
6105TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
6106 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006107 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
6108 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00006109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6110
6111 touch();
6112
6113 mTouchWindow->consumeAnyMotionDown();
6114}
6115
6116TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
6117 const sp<FakeWindowHandle>& w =
6118 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
6119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6120
6121 touch();
6122
6123 mTouchWindow->consumeAnyMotionDown();
6124}
6125
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006126TEST_F(InputDispatcherUntrustedTouchesTest,
6127 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
6128 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6129 const sp<FakeWindowHandle>& w =
6130 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
6131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6132
6133 touch();
6134
6135 mTouchWindow->assertNoEvents();
6136}
6137
6138TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
6139 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
6140 const sp<FakeWindowHandle>& w =
6141 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
6142 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6143
6144 touch();
6145
6146 mTouchWindow->consumeAnyMotionDown();
6147}
6148
6149TEST_F(InputDispatcherUntrustedTouchesTest,
6150 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
6151 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
6152 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00006153 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6154 OPACITY_ABOVE_THRESHOLD);
6155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6156
6157 touch();
6158
6159 mTouchWindow->consumeAnyMotionDown();
6160}
6161
6162TEST_F(InputDispatcherUntrustedTouchesTest,
6163 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
6164 const sp<FakeWindowHandle>& w1 =
6165 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6166 OPACITY_BELOW_THRESHOLD);
6167 const sp<FakeWindowHandle>& w2 =
6168 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
6169 OPACITY_BELOW_THRESHOLD);
6170 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
6171
6172 touch();
6173
6174 mTouchWindow->assertNoEvents();
6175}
6176
6177/**
6178 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
6179 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
6180 * (which alone would result in allowing touches) does not affect the blocking behavior.
6181 */
6182TEST_F(InputDispatcherUntrustedTouchesTest,
6183 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
6184 const sp<FakeWindowHandle>& wB =
6185 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
6186 OPACITY_BELOW_THRESHOLD);
6187 const sp<FakeWindowHandle>& wC =
6188 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6189 OPACITY_BELOW_THRESHOLD);
6190 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6191
6192 touch();
6193
6194 mTouchWindow->assertNoEvents();
6195}
6196
6197/**
6198 * This test is testing that a window from a different UID but with same application token doesn't
6199 * block the touch. Apps can share the application token for close UI collaboration for example.
6200 */
6201TEST_F(InputDispatcherUntrustedTouchesTest,
6202 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6203 const sp<FakeWindowHandle>& w =
6204 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6205 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006206 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6207
6208 touch();
6209
6210 mTouchWindow->consumeAnyMotionDown();
6211}
6212
arthurhungb89ccb02020-12-30 16:19:01 +08006213class InputDispatcherDragTests : public InputDispatcherTest {
6214protected:
6215 std::shared_ptr<FakeApplicationHandle> mApp;
6216 sp<FakeWindowHandle> mWindow;
6217 sp<FakeWindowHandle> mSecondWindow;
6218 sp<FakeWindowHandle> mDragWindow;
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006219 sp<FakeWindowHandle> mSpyWindow;
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006220 // Mouse would force no-split, set the id as non-zero to verify if drag state could track it.
6221 static constexpr int32_t MOUSE_POINTER_ID = 1;
arthurhungb89ccb02020-12-30 16:19:01 +08006222
6223 void SetUp() override {
6224 InputDispatcherTest::SetUp();
6225 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006226 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006227 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006228
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006229 mSecondWindow =
6230 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
arthurhungb89ccb02020-12-30 16:19:01 +08006231 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006232
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006233 mSpyWindow =
6234 sp<FakeWindowHandle>::make(mApp, mDispatcher, "SpyWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006235 mSpyWindow->setSpy(true);
6236 mSpyWindow->setTrustedOverlay(true);
6237 mSpyWindow->setFrame(Rect(0, 0, 200, 100));
6238
arthurhungb89ccb02020-12-30 16:19:01 +08006239 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006241 }
6242
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006243 void injectDown(int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
6244 switch (fromSource) {
6245 case AINPUT_SOURCE_TOUCHSCREEN:
6246 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6247 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN,
6248 ADISPLAY_ID_DEFAULT, {50, 50}))
6249 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6250 break;
6251 case AINPUT_SOURCE_STYLUS:
6252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6253 injectMotionEvent(
6254 mDispatcher,
6255 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6256 AINPUT_SOURCE_STYLUS)
6257 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6258 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6259 .x(50)
6260 .y(50))
6261 .build()));
6262 break;
6263 case AINPUT_SOURCE_MOUSE:
6264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6265 injectMotionEvent(
6266 mDispatcher,
6267 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
6268 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6269 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6270 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6271 .x(50)
6272 .y(50))
6273 .build()));
6274 break;
6275 default:
6276 FAIL() << "Source " << fromSource << " doesn't support drag and drop";
6277 }
arthurhungb89ccb02020-12-30 16:19:01 +08006278
6279 // Window should receive motion event.
6280 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006281 // Spy window should also receive motion event
6282 mSpyWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung54745652022-04-20 07:17:41 +00006283 }
6284
6285 // Start performing drag, we will create a drag window and transfer touch to it.
6286 // @param sendDown : if true, send a motion down on first window before perform drag and drop.
6287 // Returns true on success.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006288 bool startDrag(bool sendDown = true, int fromSource = AINPUT_SOURCE_TOUCHSCREEN) {
Arthur Hung54745652022-04-20 07:17:41 +00006289 if (sendDown) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006290 injectDown(fromSource);
Arthur Hung54745652022-04-20 07:17:41 +00006291 }
arthurhungb89ccb02020-12-30 16:19:01 +08006292
6293 // The drag window covers the entire display
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006294 mDragWindow =
6295 sp<FakeWindowHandle>::make(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006296 mDragWindow->setTouchableRegion(Region{{0, 0, 0, 0}});
arthurhungb89ccb02020-12-30 16:19:01 +08006297 mDispatcher->setInputWindows(
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006298 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mSpyWindow, mWindow, mSecondWindow}}});
arthurhungb89ccb02020-12-30 16:19:01 +08006299
6300 // Transfer touch focus to the drag window
Arthur Hung54745652022-04-20 07:17:41 +00006301 bool transferred =
6302 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6303 true /* isDragDrop */);
6304 if (transferred) {
6305 mWindow->consumeMotionCancel();
6306 mDragWindow->consumeMotionDown();
6307 }
6308 return transferred;
arthurhungb89ccb02020-12-30 16:19:01 +08006309 }
6310};
6311
6312TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006313 startDrag();
arthurhungb89ccb02020-12-30 16:19:01 +08006314
6315 // Move on window.
6316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6317 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6318 ADISPLAY_ID_DEFAULT, {50, 50}))
6319 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6320 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6321 mWindow->consumeDragEvent(false, 50, 50);
6322 mSecondWindow->assertNoEvents();
6323
6324 // Move to another window.
6325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6326 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6327 ADISPLAY_ID_DEFAULT, {150, 50}))
6328 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6329 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6330 mWindow->consumeDragEvent(true, 150, 50);
6331 mSecondWindow->consumeDragEvent(false, 50, 50);
6332
6333 // Move back to original window.
6334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6335 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6336 ADISPLAY_ID_DEFAULT, {50, 50}))
6337 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6338 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6339 mWindow->consumeDragEvent(false, 50, 50);
6340 mSecondWindow->consumeDragEvent(true, -50, 50);
6341
6342 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6343 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6344 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6345 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6346 mWindow->assertNoEvents();
6347 mSecondWindow->assertNoEvents();
6348}
6349
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006350TEST_F(InputDispatcherDragTests, DragEnterAndPointerDownPilfersPointers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006351 startDrag();
Vaibhav Devmurari6abcf8f2022-06-06 10:08:05 +00006352
6353 // No cancel event after drag start
6354 mSpyWindow->assertNoEvents();
6355
6356 const MotionEvent secondFingerDownEvent =
6357 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6358 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6359 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6360 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(60).y(60))
6361 .build();
6362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6363 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6364 InputEventInjectionSync::WAIT_FOR_RESULT))
6365 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6366
6367 // Receives cancel for first pointer after next pointer down
6368 mSpyWindow->consumeMotionCancel();
6369 mSpyWindow->consumeMotionDown();
6370
6371 mSpyWindow->assertNoEvents();
6372}
6373
arthurhungf452d0b2021-01-06 00:19:52 +08006374TEST_F(InputDispatcherDragTests, DragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006375 startDrag();
arthurhungf452d0b2021-01-06 00:19:52 +08006376
6377 // Move on window.
6378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6379 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6380 ADISPLAY_ID_DEFAULT, {50, 50}))
6381 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6382 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6383 mWindow->consumeDragEvent(false, 50, 50);
6384 mSecondWindow->assertNoEvents();
6385
6386 // Move to another window.
6387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6388 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6389 ADISPLAY_ID_DEFAULT, {150, 50}))
6390 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6391 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6392 mWindow->consumeDragEvent(true, 150, 50);
6393 mSecondWindow->consumeDragEvent(false, 50, 50);
6394
6395 // drop to another window.
6396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6397 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6398 {150, 50}))
6399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6400 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6401 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6402 mWindow->assertNoEvents();
6403 mSecondWindow->assertNoEvents();
6404}
6405
arthurhung6d4bed92021-03-17 11:59:33 +08006406TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006407 startDrag(true, AINPUT_SOURCE_STYLUS);
arthurhung6d4bed92021-03-17 11:59:33 +08006408
6409 // Move on window and keep button pressed.
6410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6411 injectMotionEvent(mDispatcher,
6412 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6413 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6414 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6415 .x(50)
6416 .y(50))
6417 .build()))
6418 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6419 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6420 mWindow->consumeDragEvent(false, 50, 50);
6421 mSecondWindow->assertNoEvents();
6422
6423 // Move to another window and release button, expect to drop item.
6424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6425 injectMotionEvent(mDispatcher,
6426 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6427 .buttonState(0)
6428 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6429 .x(150)
6430 .y(50))
6431 .build()))
6432 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6433 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6434 mWindow->assertNoEvents();
6435 mSecondWindow->assertNoEvents();
6436 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6437
6438 // nothing to the window.
6439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6440 injectMotionEvent(mDispatcher,
6441 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6442 .buttonState(0)
6443 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6444 .x(150)
6445 .y(50))
6446 .build()))
6447 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6448 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6449 mWindow->assertNoEvents();
6450 mSecondWindow->assertNoEvents();
6451}
6452
Arthur Hung54745652022-04-20 07:17:41 +00006453TEST_F(InputDispatcherDragTests, DragAndDropOnInvalidWindow) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006454 startDrag();
Arthur Hung6d0571e2021-04-09 20:18:16 +08006455
6456 // Set second window invisible.
6457 mSecondWindow->setVisible(false);
6458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6459
6460 // Move on window.
6461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6462 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6463 ADISPLAY_ID_DEFAULT, {50, 50}))
6464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6465 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6466 mWindow->consumeDragEvent(false, 50, 50);
6467 mSecondWindow->assertNoEvents();
6468
6469 // Move to another window.
6470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6471 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6472 ADISPLAY_ID_DEFAULT, {150, 50}))
6473 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6474 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6475 mWindow->consumeDragEvent(true, 150, 50);
6476 mSecondWindow->assertNoEvents();
6477
6478 // drop to another window.
6479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6480 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6481 {150, 50}))
6482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6483 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6484 mFakePolicy->assertDropTargetEquals(nullptr);
6485 mWindow->assertNoEvents();
6486 mSecondWindow->assertNoEvents();
6487}
6488
Arthur Hung54745652022-04-20 07:17:41 +00006489TEST_F(InputDispatcherDragTests, NoDragAndDropWhenMultiFingers) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006490 // Ensure window could track pointerIds if it didn't support split touch.
6491 mWindow->setPreventSplitting(true);
6492
Arthur Hung54745652022-04-20 07:17:41 +00006493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6495 {50, 50}))
6496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6497 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6498
6499 const MotionEvent secondFingerDownEvent =
6500 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6501 .displayId(ADISPLAY_ID_DEFAULT)
6502 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6503 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6504 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(75).y(50))
6505 .build();
6506 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6507 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6508 InputEventInjectionSync::WAIT_FOR_RESULT))
6509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6510 mWindow->consumeMotionPointerDown(1 /* pointerIndex */);
6511
6512 // Should not perform drag and drop when window has multi fingers.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006513 ASSERT_FALSE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006514}
6515
6516TEST_F(InputDispatcherDragTests, DragAndDropWhenSplitTouch) {
6517 // First down on second window.
6518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6520 {150, 50}))
6521 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6522
6523 mSecondWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6524
6525 // Second down on first window.
6526 const MotionEvent secondFingerDownEvent =
6527 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
6528 .displayId(ADISPLAY_ID_DEFAULT)
6529 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6530 .pointer(
6531 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6532 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6533 .build();
6534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6535 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6536 InputEventInjectionSync::WAIT_FOR_RESULT))
6537 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6538 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6539
6540 // Perform drag and drop from first window.
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006541 ASSERT_TRUE(startDrag(false));
Arthur Hung54745652022-04-20 07:17:41 +00006542
6543 // Move on window.
6544 const MotionEvent secondFingerMoveEvent =
6545 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
6546 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6547 .pointer(
6548 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6549 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6550 .build();
6551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6552 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
6553 InputEventInjectionSync::WAIT_FOR_RESULT));
6554 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6555 mWindow->consumeDragEvent(false, 50, 50);
6556 mSecondWindow->consumeMotionMove();
6557
6558 // Release the drag pointer should perform drop.
6559 const MotionEvent secondFingerUpEvent =
6560 MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
6561 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6562 .pointer(
6563 PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6564 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6565 .build();
6566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6567 injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
6568 InputEventInjectionSync::WAIT_FOR_RESULT));
6569 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6570 mFakePolicy->assertDropTargetEquals(mWindow->getToken());
6571 mWindow->assertNoEvents();
6572 mSecondWindow->consumeMotionMove();
6573}
6574
Arthur Hung3915c1f2022-05-31 07:17:17 +00006575TEST_F(InputDispatcherDragTests, DragAndDropWhenMultiDisplays) {
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006576 startDrag();
Arthur Hung3915c1f2022-05-31 07:17:17 +00006577
6578 // Update window of second display.
6579 sp<FakeWindowHandle> windowInSecondary =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006580 sp<FakeWindowHandle>::make(mApp, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung3915c1f2022-05-31 07:17:17 +00006581 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6582
6583 // Let second display has a touch state.
6584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6585 injectMotionEvent(mDispatcher,
6586 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6587 AINPUT_SOURCE_TOUCHSCREEN)
6588 .displayId(SECOND_DISPLAY_ID)
6589 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6590 .x(100)
6591 .y(100))
6592 .build()));
6593 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
6594 SECOND_DISPLAY_ID, 0 /* expectedFlag */);
6595 // Update window again.
6596 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
6597
6598 // Move on window.
6599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6600 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6601 ADISPLAY_ID_DEFAULT, {50, 50}))
6602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6603 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6604 mWindow->consumeDragEvent(false, 50, 50);
6605 mSecondWindow->assertNoEvents();
6606
6607 // Move to another window.
6608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6609 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6610 ADISPLAY_ID_DEFAULT, {150, 50}))
6611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6612 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6613 mWindow->consumeDragEvent(true, 150, 50);
6614 mSecondWindow->consumeDragEvent(false, 50, 50);
6615
6616 // drop to another window.
6617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6618 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6619 {150, 50}))
6620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6621 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6622 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6623 mWindow->assertNoEvents();
6624 mSecondWindow->assertNoEvents();
6625}
6626
Arthur Hungb75c2aa2022-07-15 09:35:36 +00006627TEST_F(InputDispatcherDragTests, MouseDragAndDrop) {
6628 startDrag(true, AINPUT_SOURCE_MOUSE);
6629 // Move on window.
6630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6631 injectMotionEvent(mDispatcher,
6632 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6633 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6634 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6635 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6636 .x(50)
6637 .y(50))
6638 .build()))
6639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6640 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6641 mWindow->consumeDragEvent(false, 50, 50);
6642 mSecondWindow->assertNoEvents();
6643
6644 // Move to another window.
6645 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6646 injectMotionEvent(mDispatcher,
6647 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_MOUSE)
6648 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
6649 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6650 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6651 .x(150)
6652 .y(50))
6653 .build()))
6654 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6655 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6656 mWindow->consumeDragEvent(true, 150, 50);
6657 mSecondWindow->consumeDragEvent(false, 50, 50);
6658
6659 // drop to another window.
6660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6661 injectMotionEvent(mDispatcher,
6662 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
6663 .buttonState(0)
6664 .pointer(PointerBuilder(MOUSE_POINTER_ID,
6665 AMOTION_EVENT_TOOL_TYPE_MOUSE)
6666 .x(150)
6667 .y(50))
6668 .build()))
6669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6670 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6671 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6672 mWindow->assertNoEvents();
6673 mSecondWindow->assertNoEvents();
6674}
6675
Vishnu Nair062a8672021-09-03 16:07:44 -07006676class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6677
6678TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6679 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006680 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6681 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006682 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006683 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6684 window->setFocusable(true);
6685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6686 setFocusedWindow(window);
6687 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6688
6689 // With the flag set, window should not get any input
6690 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6691 mDispatcher->notifyKey(&keyArgs);
6692 window->assertNoEvents();
6693
6694 NotifyMotionArgs motionArgs =
6695 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6696 ADISPLAY_ID_DEFAULT);
6697 mDispatcher->notifyMotion(&motionArgs);
6698 window->assertNoEvents();
6699
6700 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006701 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6703
6704 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6705 mDispatcher->notifyKey(&keyArgs);
6706 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6707
6708 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6709 ADISPLAY_ID_DEFAULT);
6710 mDispatcher->notifyMotion(&motionArgs);
6711 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6712 window->assertNoEvents();
6713}
6714
6715TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6716 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6717 std::make_shared<FakeApplicationHandle>();
6718 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006719 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6720 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006721 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6722 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006723 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006724 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006725 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6726 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006727 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006728 window->setOwnerInfo(222, 222);
6729 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6730 window->setFocusable(true);
6731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6732 setFocusedWindow(window);
6733 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6734
6735 // With the flag set, window should not get any input
6736 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6737 mDispatcher->notifyKey(&keyArgs);
6738 window->assertNoEvents();
6739
6740 NotifyMotionArgs motionArgs =
6741 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6742 ADISPLAY_ID_DEFAULT);
6743 mDispatcher->notifyMotion(&motionArgs);
6744 window->assertNoEvents();
6745
6746 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006747 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6749
6750 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6751 mDispatcher->notifyKey(&keyArgs);
6752 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6753
6754 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6755 ADISPLAY_ID_DEFAULT);
6756 mDispatcher->notifyMotion(&motionArgs);
6757 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6758 window->assertNoEvents();
6759}
6760
6761TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6762 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6763 std::make_shared<FakeApplicationHandle>();
6764 sp<FakeWindowHandle> obscuringWindow =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006765 sp<FakeWindowHandle>::make(obscuringApplication, mDispatcher, "obscuringWindow",
6766 ADISPLAY_ID_DEFAULT);
Vishnu Nair062a8672021-09-03 16:07:44 -07006767 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6768 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006769 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006771 sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
6772 "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006773 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006774 window->setOwnerInfo(222, 222);
6775 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6776 window->setFocusable(true);
6777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6778 setFocusedWindow(window);
6779 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6780
6781 // With the flag set, window should not get any input
6782 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6783 mDispatcher->notifyKey(&keyArgs);
6784 window->assertNoEvents();
6785
6786 NotifyMotionArgs motionArgs =
6787 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6788 ADISPLAY_ID_DEFAULT);
6789 mDispatcher->notifyMotion(&motionArgs);
6790 window->assertNoEvents();
6791
6792 // When the window is no longer obscured because it went on top, it should get input
6793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6794
6795 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6796 mDispatcher->notifyKey(&keyArgs);
6797 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6798
6799 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6800 ADISPLAY_ID_DEFAULT);
6801 mDispatcher->notifyMotion(&motionArgs);
6802 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6803 window->assertNoEvents();
6804}
6805
Antonio Kantekf16f2832021-09-28 04:39:20 +00006806class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6807protected:
6808 std::shared_ptr<FakeApplicationHandle> mApp;
6809 sp<FakeWindowHandle> mWindow;
6810 sp<FakeWindowHandle> mSecondWindow;
6811
6812 void SetUp() override {
6813 InputDispatcherTest::SetUp();
6814
6815 mApp = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006816 mWindow = sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006817 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006818 setFocusedWindow(mWindow);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006819 mSecondWindow =
6820 sp<FakeWindowHandle>::make(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006821 mSecondWindow->setFocusable(true);
6822
6823 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006825 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006826
6827 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan5735a322022-04-11 17:23:34 +00006828 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, WINDOW_PID,
Antonio Kanteka042c022022-07-06 16:51:07 -07006829 WINDOW_UID, true /*hasPermission*/, ADISPLAY_ID_DEFAULT)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006830 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6831 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6832 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006833 }
6834
Antonio Kantekea47acb2021-12-23 12:41:25 -08006835 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kanteka042c022022-07-06 16:51:07 -07006836 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission,
6837 ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006838 mWindow->consumeTouchModeEvent(inTouchMode);
6839 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6840 }
6841};
6842
Antonio Kantek26defcf2022-02-08 01:12:27 +00006843TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006844 const WindowInfo& windowInfo = *mWindow->getInfo();
6845 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006846 windowInfo.ownerUid, false /*hasPermission*/);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006847}
6848
Antonio Kantek26defcf2022-02-08 01:12:27 +00006849TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6850 const WindowInfo& windowInfo = *mWindow->getInfo();
6851 int32_t ownerPid = windowInfo.ownerPid;
6852 int32_t ownerUid = windowInfo.ownerUid;
6853 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6854 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006855 ownerUid, false /*hasPermission*/,
6856 ADISPLAY_ID_DEFAULT));
Antonio Kantek26defcf2022-02-08 01:12:27 +00006857 mWindow->assertNoEvents();
6858 mSecondWindow->assertNoEvents();
6859}
6860
6861TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6862 const WindowInfo& windowInfo = *mWindow->getInfo();
6863 int32_t ownerPid = windowInfo.ownerPid;
6864 int32_t ownerUid = windowInfo.ownerUid;
6865 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6866 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006867 true /*hasPermission*/);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006868}
6869
Antonio Kantekf16f2832021-09-28 04:39:20 +00006870TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006871 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006872 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6873 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006874 true /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006875 mWindow->assertNoEvents();
6876 mSecondWindow->assertNoEvents();
6877}
6878
Antonio Kantek48710e42022-03-24 14:19:30 -07006879TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6880 // Interact with the window first.
6881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6882 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6883 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6884
6885 // Then remove focus.
6886 mWindow->setFocusable(false);
6887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6888
6889 // Assert that caller can switch touch mode by owning one of the last interacted window.
6890 const WindowInfo& windowInfo = *mWindow->getInfo();
6891 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6892 windowInfo.ownerPid, windowInfo.ownerUid,
Antonio Kanteka042c022022-07-06 16:51:07 -07006893 false /*hasPermission*/, ADISPLAY_ID_DEFAULT));
Antonio Kantek48710e42022-03-24 14:19:30 -07006894}
6895
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006896class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6897public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006898 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006899 std::shared_ptr<FakeApplicationHandle> application =
6900 std::make_shared<FakeApplicationHandle>();
6901 std::string name = "Fake Spy ";
6902 name += std::to_string(mSpyCount++);
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006903 sp<FakeWindowHandle> spy = sp<FakeWindowHandle>::make(application, mDispatcher,
6904 name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006905 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006906 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006907 return spy;
6908 }
6909
6910 sp<FakeWindowHandle> createForeground() {
6911 std::shared_ptr<FakeApplicationHandle> application =
6912 std::make_shared<FakeApplicationHandle>();
6913 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07006914 sp<FakeWindowHandle>::make(application, mDispatcher, "Fake Window",
6915 ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006916 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006917 return window;
6918 }
6919
6920private:
6921 int mSpyCount{0};
6922};
6923
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006924using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006925/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006926 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6927 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006928TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6929 ScopedSilentDeath _silentDeath;
6930
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006931 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006932 spy->setTrustedOverlay(false);
6933 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6934 ".* not a trusted overlay");
6935}
6936
6937/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006938 * Input injection into a display with a spy window but no foreground windows should succeed.
6939 */
6940TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006941 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6943
6944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6947 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6948}
6949
6950/**
6951 * Verify the order in which different input windows receive events. The touched foreground window
6952 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6953 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6954 * receive events before ones belows it.
6955 *
6956 * Here, we set up a scenario with four windows in the following Z order from the top:
6957 * spy1, spy2, window, spy3.
6958 * We then inject an event and verify that the foreground "window" receives it first, followed by
6959 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6960 * window.
6961 */
6962TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6963 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006964 auto spy1 = createSpy();
6965 auto spy2 = createSpy();
6966 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006967 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6968 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6969 const size_t numChannels = channels.size();
6970
Michael Wright8e9a8562022-02-09 13:44:29 +00006971 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006972 if (!epollFd.ok()) {
6973 FAIL() << "Failed to create epoll fd";
6974 }
6975
6976 for (size_t i = 0; i < numChannels; i++) {
6977 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6978 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6979 FAIL() << "Failed to add fd to epoll";
6980 }
6981 }
6982
6983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6984 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6985 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6986
6987 std::vector<size_t> eventOrder;
6988 std::vector<struct epoll_event> events(numChannels);
6989 for (;;) {
6990 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6991 (100ms).count());
6992 if (nFds < 0) {
6993 FAIL() << "Failed to call epoll_wait";
6994 }
6995 if (nFds == 0) {
6996 break; // epoll_wait timed out
6997 }
6998 for (int i = 0; i < nFds; i++) {
6999 ASSERT_EQ(EPOLLIN, events[i].events);
7000 eventOrder.push_back(events[i].data.u64);
7001 channels[i]->consumeMotionDown();
7002 }
7003 }
7004
7005 // Verify the order in which the events were received.
7006 EXPECT_EQ(3u, eventOrder.size());
7007 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
7008 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
7009 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
7010}
7011
7012/**
7013 * A spy window using the NOT_TOUCHABLE flag does not receive events.
7014 */
7015TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
7016 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007017 auto spy = createSpy();
7018 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7020
7021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7022 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7023 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7024 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7025 spy->assertNoEvents();
7026}
7027
7028/**
7029 * A spy window will only receive gestures that originate within its touchable region. Gestures that
7030 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
7031 * to the window.
7032 */
7033TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
7034 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007035 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007036 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
7037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7038
7039 // Inject an event outside the spy window's touchable region.
7040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7041 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7043 window->consumeMotionDown();
7044 spy->assertNoEvents();
7045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7046 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7048 window->consumeMotionUp();
7049 spy->assertNoEvents();
7050
7051 // Inject an event inside the spy window's touchable region.
7052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7053 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7054 {5, 10}))
7055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7056 window->consumeMotionDown();
7057 spy->consumeMotionDown();
7058}
7059
7060/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007061 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007062 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007063 */
7064TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
7065 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007066 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007067 auto spy = createSpy();
7068 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007069 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007070 spy->setFrame(Rect{0, 0, 20, 20});
7071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7072
7073 // Inject an event outside the spy window's frame and touchable region.
7074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7076 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007077 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7078 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08007079 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007080}
7081
7082/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007083 * Even when a spy window spans over multiple foreground windows, the spy should receive all
7084 * pointers that are down within its bounds.
7085 */
7086TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
7087 auto windowLeft = createForeground();
7088 windowLeft->setFrame({0, 0, 100, 200});
7089 auto windowRight = createForeground();
7090 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007091 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007092 spy->setFrame({0, 0, 200, 200});
7093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
7094
7095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7096 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7097 {50, 50}))
7098 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7099 windowLeft->consumeMotionDown();
7100 spy->consumeMotionDown();
7101
7102 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007103 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007104 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7105 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7106 .pointer(
7107 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7108 .build();
7109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7110 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7111 InputEventInjectionSync::WAIT_FOR_RESULT))
7112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7113 windowRight->consumeMotionDown();
7114 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7115}
7116
7117/**
7118 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
7119 * the spy should receive the second pointer with ACTION_DOWN.
7120 */
7121TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
7122 auto window = createForeground();
7123 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007124 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007125 spyRight->setFrame({100, 0, 200, 200});
7126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
7127
7128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7129 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7130 {50, 50}))
7131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7132 window->consumeMotionDown();
7133 spyRight->assertNoEvents();
7134
7135 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007136 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08007137 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7138 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7139 .pointer(
7140 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
7141 .build();
7142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7143 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7144 InputEventInjectionSync::WAIT_FOR_RESULT))
7145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7146 window->consumeMotionPointerDown(1 /*pointerIndex*/);
7147 spyRight->consumeMotionDown();
7148}
7149
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007150/**
7151 * The spy window should not be able to affect whether or not touches are split. Only the foreground
7152 * windows should be allowed to control split touch.
7153 */
7154TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007155 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007156 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007157 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08007158 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007159
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007160 auto window = createForeground();
7161 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007162
7163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7164
7165 // First finger down, no window touched.
7166 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7167 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7168 {100, 200}))
7169 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7170 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7171 window->assertNoEvents();
7172
7173 // Second finger down on window, the window should receive touch down.
7174 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08007175 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007176 .displayId(ADISPLAY_ID_DEFAULT)
7177 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7178 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7179 .x(100)
7180 .y(200))
7181 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7182 .build();
7183 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7184 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7185 InputEventInjectionSync::WAIT_FOR_RESULT))
7186 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7187
7188 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7189 spy->consumeMotionPointerDown(1 /* pointerIndex */);
7190}
7191
7192/**
7193 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
7194 * do not receive key events.
7195 */
7196TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007197 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08007198 spy->setFocusable(false);
7199
7200 auto window = createForeground();
7201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7202 setFocusedWindow(window);
7203 window->consumeFocusEvent(true);
7204
7205 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
7206 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7207 window->consumeKeyDown(ADISPLAY_ID_NONE);
7208
7209 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
7210 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
7211 window->consumeKeyUp(ADISPLAY_ID_NONE);
7212
7213 spy->assertNoEvents();
7214}
7215
Vaibhav Devmurariff798f32022-05-09 23:45:04 +00007216using InputDispatcherPilferPointersTest = InputDispatcherSpyWindowTest;
7217
7218/**
7219 * A spy window can pilfer pointers. When this happens, touch gestures used by the spy window that
7220 * are currently sent to any other windows - including other spy windows - will also be cancelled.
7221 */
7222TEST_F(InputDispatcherPilferPointersTest, PilferPointers) {
7223 auto window = createForeground();
7224 auto spy1 = createSpy();
7225 auto spy2 = createSpy();
7226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
7227
7228 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7229 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7230 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7231 window->consumeMotionDown();
7232 spy1->consumeMotionDown();
7233 spy2->consumeMotionDown();
7234
7235 // Pilfer pointers from the second spy window.
7236 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
7237 spy2->assertNoEvents();
7238 spy1->consumeMotionCancel();
7239 window->consumeMotionCancel();
7240
7241 // The rest of the gesture should only be sent to the second spy window.
7242 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7243 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
7244 ADISPLAY_ID_DEFAULT))
7245 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7246 spy2->consumeMotionMove();
7247 spy1->assertNoEvents();
7248 window->assertNoEvents();
7249}
7250
7251/**
7252 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
7253 * in the middle of the gesture.
7254 */
7255TEST_F(InputDispatcherPilferPointersTest, CanPilferAfterWindowIsRemovedMidStream) {
7256 auto window = createForeground();
7257 auto spy = createSpy();
7258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7259
7260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7261 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7262 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7263 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7264 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
7265
7266 window->releaseChannel();
7267
7268 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7269
7270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7271 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
7272 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7273 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
7274}
7275
7276/**
7277 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
7278 * the spy, but not to any other windows.
7279 */
7280TEST_F(InputDispatcherPilferPointersTest, ContinuesToReceiveGestureAfterPilfer) {
7281 auto spy = createSpy();
7282 auto window = createForeground();
7283
7284 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7285
7286 // First finger down on the window and the spy.
7287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7288 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7289 {100, 200}))
7290 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7291 spy->consumeMotionDown();
7292 window->consumeMotionDown();
7293
7294 // Spy window pilfers the pointers.
7295 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7296 window->consumeMotionCancel();
7297
7298 // Second finger down on the window and spy, but the window should not receive the pointer down.
7299 const MotionEvent secondFingerDownEvent =
7300 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7301 .displayId(ADISPLAY_ID_DEFAULT)
7302 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7303 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7304 .x(100)
7305 .y(200))
7306 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7307 .build();
7308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7309 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7310 InputEventInjectionSync::WAIT_FOR_RESULT))
7311 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7312
7313 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
7314
7315 // Third finger goes down outside all windows, so injection should fail.
7316 const MotionEvent thirdFingerDownEvent =
7317 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7318 .displayId(ADISPLAY_ID_DEFAULT)
7319 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7320 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7321 .x(100)
7322 .y(200))
7323 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7324 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
7325 .build();
7326 ASSERT_EQ(InputEventInjectionResult::FAILED,
7327 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7328 InputEventInjectionSync::WAIT_FOR_RESULT))
7329 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7330
7331 spy->assertNoEvents();
7332 window->assertNoEvents();
7333}
7334
7335/**
7336 * After a spy window pilfers pointers, only the pointers used by the spy should be canceled
7337 */
7338TEST_F(InputDispatcherPilferPointersTest, PartiallyPilferRequiredPointers) {
7339 auto spy = createSpy();
7340 spy->setFrame(Rect(0, 0, 100, 100));
7341 auto window = createForeground();
7342 window->setFrame(Rect(0, 0, 200, 200));
7343
7344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7345
7346 // First finger down on the window only
7347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7348 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7349 {150, 150}))
7350 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7351 window->consumeMotionDown();
7352
7353 // Second finger down on the spy and window
7354 const MotionEvent secondFingerDownEvent =
7355 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7356 .displayId(ADISPLAY_ID_DEFAULT)
7357 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7358 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7359 .x(150)
7360 .y(150))
7361 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7362 .build();
7363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7364 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7365 InputEventInjectionSync::WAIT_FOR_RESULT))
7366 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7367 spy->consumeMotionDown();
7368 window->consumeMotionPointerDown(1);
7369
7370 // Third finger down on the spy and window
7371 const MotionEvent thirdFingerDownEvent =
7372 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7373 .displayId(ADISPLAY_ID_DEFAULT)
7374 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7375 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
7376 .x(150)
7377 .y(150))
7378 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7379 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7380 .build();
7381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7382 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
7383 InputEventInjectionSync::WAIT_FOR_RESULT))
7384 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7385 spy->consumeMotionPointerDown(1);
7386 window->consumeMotionPointerDown(2);
7387
7388 // Spy window pilfers the pointers.
7389 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7390 window->consumeMotionPointerUp(/* idx */ 2, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7391 window->consumeMotionPointerUp(/* idx */ 1, ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
7392
7393 spy->assertNoEvents();
7394 window->assertNoEvents();
7395}
7396
7397/**
7398 * After a spy window pilfers pointers, all pilfered pointers that have already been dispatched to
7399 * other windows should be canceled. If this results in the cancellation of all pointers for some
7400 * window, then that window should receive ACTION_CANCEL.
7401 */
7402TEST_F(InputDispatcherPilferPointersTest, PilferAllRequiredPointers) {
7403 auto spy = createSpy();
7404 spy->setFrame(Rect(0, 0, 100, 100));
7405 auto window = createForeground();
7406 window->setFrame(Rect(0, 0, 200, 200));
7407
7408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7409
7410 // First finger down on both spy and window
7411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7412 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7413 {10, 10}))
7414 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7415 window->consumeMotionDown();
7416 spy->consumeMotionDown();
7417
7418 // Second finger down on the spy and window
7419 const MotionEvent secondFingerDownEvent =
7420 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7421 .displayId(ADISPLAY_ID_DEFAULT)
7422 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7423 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7424 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
7425 .build();
7426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7427 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7428 InputEventInjectionSync::WAIT_FOR_RESULT))
7429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7430 spy->consumeMotionPointerDown(1);
7431 window->consumeMotionPointerDown(1);
7432
7433 // Spy window pilfers the pointers.
7434 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7435 window->consumeMotionCancel();
7436
7437 spy->assertNoEvents();
7438 window->assertNoEvents();
7439}
7440
7441/**
7442 * After a spy window pilfers pointers, new pointers that are not touching the spy window can still
7443 * be sent to other windows
7444 */
7445TEST_F(InputDispatcherPilferPointersTest, CanReceivePointersAfterPilfer) {
7446 auto spy = createSpy();
7447 spy->setFrame(Rect(0, 0, 100, 100));
7448 auto window = createForeground();
7449 window->setFrame(Rect(0, 0, 200, 200));
7450
7451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7452
7453 // First finger down on both window and spy
7454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7455 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
7456 {10, 10}))
7457 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7458 window->consumeMotionDown();
7459 spy->consumeMotionDown();
7460
7461 // Spy window pilfers the pointers.
7462 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
7463 window->consumeMotionCancel();
7464
7465 // Second finger down on the window only
7466 const MotionEvent secondFingerDownEvent =
7467 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
7468 .displayId(ADISPLAY_ID_DEFAULT)
7469 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
7470 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
7471 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
7472 .x(150)
7473 .y(150))
7474 .build();
7475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
7476 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
7477 InputEventInjectionSync::WAIT_FOR_RESULT))
7478 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
7479 window->consumeMotionDown();
7480 window->assertNoEvents();
7481
7482 // TODO(b/232530217): do not send the unnecessary MOVE event and delete the next line
7483 spy->consumeMotionMove();
7484 spy->assertNoEvents();
7485}
7486
Prabir Pradhand65552b2021-10-07 11:23:50 -07007487class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
7488public:
7489 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
7490 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7491 std::make_shared<FakeApplicationHandle>();
7492 sp<FakeWindowHandle> overlay =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007493 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher,
7494 "Stylus interceptor window", ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007495 overlay->setFocusable(false);
7496 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08007497 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007498 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007499 overlay->setTrustedOverlay(true);
7500
7501 std::shared_ptr<FakeApplicationHandle> application =
7502 std::make_shared<FakeApplicationHandle>();
7503 sp<FakeWindowHandle> window =
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007504 sp<FakeWindowHandle>::make(application, mDispatcher, "Application window",
7505 ADISPLAY_ID_DEFAULT);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007506 window->setFocusable(true);
7507 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007508
7509 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
7510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7511 setFocusedWindow(window);
7512 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
7513 return {std::move(overlay), std::move(window)};
7514 }
7515
7516 void sendFingerEvent(int32_t action) {
7517 NotifyMotionArgs motionArgs =
7518 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7519 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
7520 mDispatcher->notifyMotion(&motionArgs);
7521 }
7522
7523 void sendStylusEvent(int32_t action) {
7524 NotifyMotionArgs motionArgs =
7525 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
7526 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
7527 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7528 mDispatcher->notifyMotion(&motionArgs);
7529 }
7530};
7531
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08007532using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
7533
7534TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
7535 ScopedSilentDeath _silentDeath;
7536
Prabir Pradhand65552b2021-10-07 11:23:50 -07007537 auto [overlay, window] = setupStylusOverlayScenario();
7538 overlay->setTrustedOverlay(false);
7539 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
7540 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
7541 ".* not a trusted overlay");
7542}
7543
7544TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
7545 auto [overlay, window] = setupStylusOverlayScenario();
7546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7547
7548 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7549 overlay->consumeMotionDown();
7550 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7551 overlay->consumeMotionUp();
7552
7553 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7554 window->consumeMotionDown();
7555 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7556 window->consumeMotionUp();
7557
7558 overlay->assertNoEvents();
7559 window->assertNoEvents();
7560}
7561
7562TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
7563 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08007564 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07007565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7566
7567 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7568 overlay->consumeMotionDown();
7569 window->consumeMotionDown();
7570 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7571 overlay->consumeMotionUp();
7572 window->consumeMotionUp();
7573
7574 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
7575 window->consumeMotionDown();
7576 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
7577 window->consumeMotionUp();
7578
7579 overlay->assertNoEvents();
7580 window->assertNoEvents();
7581}
7582
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00007583/**
7584 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
7585 * The scenario is as follows:
7586 * - The stylus interceptor overlay is configured as a spy window.
7587 * - The stylus interceptor spy receives the start of a new stylus gesture.
7588 * - It pilfers pointers and then configures itself to no longer be a spy.
7589 * - The stylus interceptor continues to receive the rest of the gesture.
7590 */
7591TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
7592 auto [overlay, window] = setupStylusOverlayScenario();
7593 overlay->setSpy(true);
7594 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7595
7596 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
7597 overlay->consumeMotionDown();
7598 window->consumeMotionDown();
7599
7600 // The interceptor pilfers the pointers.
7601 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
7602 window->consumeMotionCancel();
7603
7604 // The interceptor configures itself so that it is no longer a spy.
7605 overlay->setSpy(false);
7606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7607
7608 // It continues to receive the rest of the stylus gesture.
7609 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7610 overlay->consumeMotionMove();
7611 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7612 overlay->consumeMotionUp();
7613
7614 window->assertNoEvents();
7615}
7616
Prabir Pradhan5735a322022-04-11 17:23:34 +00007617struct User {
7618 int32_t mPid;
7619 int32_t mUid;
7620 uint32_t mPolicyFlags{DEFAULT_POLICY_FLAGS};
7621 std::unique_ptr<InputDispatcher>& mDispatcher;
7622
7623 User(std::unique_ptr<InputDispatcher>& dispatcher, int32_t pid, int32_t uid)
7624 : mPid(pid), mUid(uid), mDispatcher(dispatcher) {}
7625
7626 InputEventInjectionResult injectTargetedMotion(int32_t action) const {
7627 return injectMotionEvent(mDispatcher, action, AINPUT_SOURCE_TOUCHSCREEN,
7628 ADISPLAY_ID_DEFAULT, {100, 200},
7629 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
7630 AMOTION_EVENT_INVALID_CURSOR_POSITION},
7631 INJECT_EVENT_TIMEOUT, InputEventInjectionSync::WAIT_FOR_RESULT,
7632 systemTime(SYSTEM_TIME_MONOTONIC), {mUid}, mPolicyFlags);
7633 }
7634
7635 InputEventInjectionResult injectTargetedKey(int32_t action) const {
7636 return inputdispatcher::injectKey(mDispatcher, action, 0 /* repeatCount*/, ADISPLAY_ID_NONE,
7637 InputEventInjectionSync::WAIT_FOR_RESULT,
7638 INJECT_EVENT_TIMEOUT, false /*allowKeyRepeat*/, {mUid},
7639 mPolicyFlags);
7640 }
7641
7642 sp<FakeWindowHandle> createWindow() const {
7643 std::shared_ptr<FakeApplicationHandle> overlayApplication =
7644 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouaed7ad02022-08-03 15:04:33 -07007645 sp<FakeWindowHandle> window =
7646 sp<FakeWindowHandle>::make(overlayApplication, mDispatcher, "Owned Window",
7647 ADISPLAY_ID_DEFAULT);
Prabir Pradhan5735a322022-04-11 17:23:34 +00007648 window->setOwnerInfo(mPid, mUid);
7649 return window;
7650 }
7651};
7652
7653using InputDispatcherTargetedInjectionTest = InputDispatcherTest;
7654
7655TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedWindow) {
7656 auto owner = User(mDispatcher, 10, 11);
7657 auto window = owner.createWindow();
7658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7659
7660 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7661 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7662 window->consumeMotionDown();
7663
7664 setFocusedWindow(window);
7665 window->consumeFocusEvent(true);
7666
7667 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7668 owner.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7669 window->consumeKeyDown(ADISPLAY_ID_NONE);
7670}
7671
7672TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedWindow) {
7673 auto owner = User(mDispatcher, 10, 11);
7674 auto window = owner.createWindow();
7675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
7676
7677 auto rando = User(mDispatcher, 20, 21);
7678 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7679 rando.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7680
7681 setFocusedWindow(window);
7682 window->consumeFocusEvent(true);
7683
7684 EXPECT_EQ(InputEventInjectionResult::TARGET_MISMATCH,
7685 rando.injectTargetedKey(AKEY_EVENT_ACTION_DOWN));
7686 window->assertNoEvents();
7687}
7688
7689TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoOwnedSpyWindow) {
7690 auto owner = User(mDispatcher, 10, 11);
7691 auto window = owner.createWindow();
7692 auto spy = owner.createWindow();
7693 spy->setSpy(true);
7694 spy->setTrustedOverlay(true);
7695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
7696
7697 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7698 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7699 spy->consumeMotionDown();
7700 window->consumeMotionDown();
7701}
7702
7703TEST_F(InputDispatcherTargetedInjectionTest, CannotInjectIntoUnownedSpyWindow) {
7704 auto owner = User(mDispatcher, 10, 11);
7705 auto window = owner.createWindow();
7706
7707 auto rando = User(mDispatcher, 20, 21);
7708 auto randosSpy = rando.createWindow();
7709 randosSpy->setSpy(true);
7710 randosSpy->setTrustedOverlay(true);
7711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7712
7713 // The event is targeted at owner's window, so injection should succeed, but the spy should
7714 // not receive the event.
7715 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7716 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7717 randosSpy->assertNoEvents();
7718 window->consumeMotionDown();
7719}
7720
7721TEST_F(InputDispatcherTargetedInjectionTest, CanInjectIntoAnyWindowWhenNotTargeting) {
7722 auto owner = User(mDispatcher, 10, 11);
7723 auto window = owner.createWindow();
7724
7725 auto rando = User(mDispatcher, 20, 21);
7726 auto randosSpy = rando.createWindow();
7727 randosSpy->setSpy(true);
7728 randosSpy->setTrustedOverlay(true);
7729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosSpy, window}}});
7730
7731 // A user that has injection permission can inject into any window.
7732 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7733 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
7734 ADISPLAY_ID_DEFAULT));
7735 randosSpy->consumeMotionDown();
7736 window->consumeMotionDown();
7737
7738 setFocusedWindow(randosSpy);
7739 randosSpy->consumeFocusEvent(true);
7740
7741 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher));
7742 randosSpy->consumeKeyDown(ADISPLAY_ID_NONE);
7743 window->assertNoEvents();
7744}
7745
7746TEST_F(InputDispatcherTargetedInjectionTest, CanGenerateActionOutsideToOtherUids) {
7747 auto owner = User(mDispatcher, 10, 11);
7748 auto window = owner.createWindow();
7749
7750 auto rando = User(mDispatcher, 20, 21);
7751 auto randosWindow = rando.createWindow();
7752 randosWindow->setFrame(Rect{-10, -10, -5, -5});
7753 randosWindow->setWatchOutsideTouch(true);
7754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {randosWindow, window}}});
7755
7756 // We allow generation of ACTION_OUTSIDE events into windows owned by different uids.
7757 EXPECT_EQ(InputEventInjectionResult::SUCCEEDED,
7758 owner.injectTargetedMotion(AMOTION_EVENT_ACTION_DOWN));
7759 window->consumeMotionDown();
7760 randosWindow->consumeMotionOutside();
7761}
7762
Garfield Tane84e6f92019-08-29 17:28:41 -07007763} // namespace android::inputdispatcher