Extract FakeInputDispatcherPolicy into a separate cpp file
It will be used by other tests that will be added in the future.
Bug: 210460522
Test: build
Change-Id: I36d6b5aef98e621d8193d72063e8c7ecddd567a3
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 9e3a4f1..d77bf3d 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -16,6 +16,7 @@
#include "../dispatcher/InputDispatcher.h"
#include "FakeApplicationHandle.h"
+#include "FakeInputDispatcherPolicy.h"
#include "FakeInputTracingBackend.h"
#include "TestEventMatchers.h"
@@ -151,518 +152,6 @@
return event;
}
-// --- FakeInputDispatcherPolicy ---
-
-class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
- struct AnrResult {
- sp<IBinder> token{};
- std::optional<gui::Pid> pid{};
- };
- /* Stores data about a user-activity-poke event from the dispatcher. */
- struct UserActivityPokeEvent {
- nsecs_t eventTime;
- int32_t eventType;
- int32_t displayId;
-
- bool operator==(const UserActivityPokeEvent& rhs) const = default;
-
- friend std::ostream& operator<<(std::ostream& os, const UserActivityPokeEvent& ev) {
- os << "UserActivityPokeEvent[time=" << ev.eventTime << ", eventType=" << ev.eventType
- << ", displayId=" << ev.displayId << "]";
- return os;
- }
- };
-
-public:
- FakeInputDispatcherPolicy() = default;
- virtual ~FakeInputDispatcherPolicy() = default;
-
- void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
- assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
- ASSERT_EQ(event.getType(), InputEventType::KEY);
- EXPECT_EQ(event.getDisplayId(), args.displayId);
-
- const auto& keyEvent = static_cast<const KeyEvent&>(event);
- EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
- EXPECT_EQ(keyEvent.getAction(), args.action);
- });
- }
-
- void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
- assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
- ASSERT_EQ(event.getType(), InputEventType::MOTION);
- EXPECT_EQ(event.getDisplayId(), args.displayId);
-
- const auto& motionEvent = static_cast<const MotionEvent&>(event);
- EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
- EXPECT_EQ(motionEvent.getAction(), args.action);
- EXPECT_NEAR(motionEvent.getX(0), point.x, MotionEvent::ROUNDING_PRECISION);
- EXPECT_NEAR(motionEvent.getY(0), point.y, MotionEvent::ROUNDING_PRECISION);
- EXPECT_NEAR(motionEvent.getRawX(0), point.x, MotionEvent::ROUNDING_PRECISION);
- EXPECT_NEAR(motionEvent.getRawY(0), point.y, MotionEvent::ROUNDING_PRECISION);
- });
- }
-
- void assertFilterInputEventWasNotCalled() {
- std::scoped_lock lock(mLock);
- ASSERT_EQ(nullptr, mFilteredEvent);
- }
-
- void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
- std::scoped_lock lock(mLock);
- ASSERT_TRUE(mConfigurationChangedTime)
- << "Timed out waiting for configuration changed call";
- ASSERT_EQ(*mConfigurationChangedTime, when);
- mConfigurationChangedTime = std::nullopt;
- }
-
- void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
- std::scoped_lock lock(mLock);
- ASSERT_TRUE(mLastNotifySwitch);
- // We do not check id because it is not exposed to the policy
- EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
- EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
- EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
- EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
- mLastNotifySwitch = std::nullopt;
- }
-
- void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
- std::scoped_lock lock(mLock);
- ASSERT_EQ(touchedToken, mOnPointerDownToken);
- mOnPointerDownToken.clear();
- }
-
- void assertOnPointerDownWasNotCalled() {
- std::scoped_lock lock(mLock);
- ASSERT_TRUE(mOnPointerDownToken == nullptr)
- << "Expected onPointerDownOutsideFocus to not have been called";
- }
-
- // This function must be called soon after the expected ANR timer starts,
- // because we are also checking how much time has passed.
- void assertNotifyNoFocusedWindowAnrWasCalled(
- std::chrono::nanoseconds timeout,
- const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
- std::unique_lock lock(mLock);
- android::base::ScopedLockAssertion assumeLocked(mLock);
- std::shared_ptr<InputApplicationHandle> application;
- ASSERT_NO_FATAL_FAILURE(
- application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
- ASSERT_EQ(expectedApplication, application);
- }
-
- void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
- const sp<WindowInfoHandle>& window) {
- LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
- assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
- window->getInfo()->ownerPid);
- }
-
- void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
- const sp<IBinder>& expectedToken,
- std::optional<gui::Pid> expectedPid) {
- std::unique_lock lock(mLock);
- android::base::ScopedLockAssertion assumeLocked(mLock);
- AnrResult result;
- ASSERT_NO_FATAL_FAILURE(result =
- getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
- ASSERT_EQ(expectedToken, result.token);
- ASSERT_EQ(expectedPid, result.pid);
- }
-
- /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
- sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
- std::unique_lock lock(mLock);
- android::base::ScopedLockAssertion assumeLocked(mLock);
- AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
- const auto& [token, _] = result;
- return token;
- }
-
- void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
- std::optional<gui::Pid> expectedPid) {
- std::unique_lock lock(mLock);
- android::base::ScopedLockAssertion assumeLocked(mLock);
- AnrResult result;
- ASSERT_NO_FATAL_FAILURE(
- result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
- ASSERT_EQ(expectedToken, result.token);
- ASSERT_EQ(expectedPid, result.pid);
- }
-
- /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
- sp<IBinder> getResponsiveWindowToken() {
- std::unique_lock lock(mLock);
- android::base::ScopedLockAssertion assumeLocked(mLock);
- AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
- const auto& [token, _] = result;
- return token;
- }
-
- void assertNotifyAnrWasNotCalled() {
- std::scoped_lock lock(mLock);
- ASSERT_TRUE(mAnrApplications.empty());
- ASSERT_TRUE(mAnrWindows.empty());
- ASSERT_TRUE(mResponsiveWindows.empty())
- << "ANR was not called, but please also consume the 'connection is responsive' "
- "signal";
- }
-
- PointerCaptureRequest assertSetPointerCaptureCalled(const sp<WindowInfoHandle>& window,
- bool enabled) {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
-
- if (!mPointerCaptureChangedCondition
- .wait_for(lock, 100ms, [this, enabled, window]() REQUIRES(mLock) {
- if (enabled) {
- return mPointerCaptureRequest->isEnable() &&
- mPointerCaptureRequest->window == window->getToken();
- } else {
- return !mPointerCaptureRequest->isEnable();
- }
- })) {
- ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << window->getName() << ", "
- << enabled << ") to be called.";
- return {};
- }
- auto request = *mPointerCaptureRequest;
- mPointerCaptureRequest.reset();
- return request;
- }
-
- void assertSetPointerCaptureNotCalled() {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
-
- if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
- FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
- "enabled = "
- << std::to_string(mPointerCaptureRequest->isEnable());
- }
- mPointerCaptureRequest.reset();
- }
-
- void assertDropTargetEquals(const InputDispatcherInterface& dispatcher,
- const sp<IBinder>& targetToken) {
- dispatcher.waitForIdle();
- std::scoped_lock lock(mLock);
- ASSERT_TRUE(mNotifyDropWindowWasCalled);
- ASSERT_EQ(targetToken, mDropTargetWindowToken);
- mNotifyDropWindowWasCalled = false;
- }
-
- void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
- std::optional<sp<IBinder>> receivedToken =
- getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
- mNotifyInputChannelBroken);
- ASSERT_TRUE(receivedToken.has_value()) << "Did not receive the broken channel token";
- ASSERT_EQ(token, *receivedToken);
- }
-
- /**
- * Set policy timeout. A value of zero means next key will not be intercepted.
- */
- void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
- mInterceptKeyTimeout = timeout;
- }
-
- std::chrono::nanoseconds getKeyWaitingForEventsTimeout() override { return 500ms; }
-
- void setStaleEventTimeout(std::chrono::nanoseconds timeout) { mStaleEventTimeout = timeout; }
-
- void assertUserActivityNotPoked() {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
-
- std::optional<UserActivityPokeEvent> pokeEvent =
- getItemFromStorageLockedInterruptible(500ms, mUserActivityPokeEvents, lock,
- mNotifyUserActivity);
-
- ASSERT_FALSE(pokeEvent) << "Expected user activity not to have been poked";
- }
-
- /**
- * Asserts that a user activity poke has happened. The earliest recorded poke event will be
- * cleared after this call.
- *
- * If an expected UserActivityPokeEvent is provided, asserts that the given event is the
- * earliest recorded poke event.
- */
- void assertUserActivityPoked(std::optional<UserActivityPokeEvent> expectedPokeEvent = {}) {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
-
- std::optional<UserActivityPokeEvent> pokeEvent =
- getItemFromStorageLockedInterruptible(500ms, mUserActivityPokeEvents, lock,
- mNotifyUserActivity);
- ASSERT_TRUE(pokeEvent) << "Expected a user poke event";
-
- if (expectedPokeEvent) {
- ASSERT_EQ(expectedPokeEvent, *pokeEvent);
- }
- }
-
- void assertNotifyDeviceInteractionWasCalled(int32_t deviceId, std::set<gui::Uid> uids) {
- ASSERT_EQ(std::make_pair(deviceId, uids), mNotifiedInteractions.popWithTimeout(100ms));
- }
-
- void assertNotifyDeviceInteractionWasNotCalled() {
- ASSERT_FALSE(mNotifiedInteractions.popWithTimeout(10ms));
- }
-
- void setUnhandledKeyHandler(std::function<std::optional<KeyEvent>(const KeyEvent&)> handler) {
- std::scoped_lock lock(mLock);
- mUnhandledKeyHandler = handler;
- }
-
- void assertUnhandledKeyReported(int32_t keycode) {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
- std::optional<int32_t> unhandledKeycode =
- getItemFromStorageLockedInterruptible(100ms, mReportedUnhandledKeycodes, lock,
- mNotifyUnhandledKey);
- ASSERT_TRUE(unhandledKeycode) << "Expected unhandled key to be reported";
- ASSERT_EQ(unhandledKeycode, keycode);
- }
-
- void assertUnhandledKeyNotReported() {
- std::unique_lock lock(mLock);
- base::ScopedLockAssertion assumeLocked(mLock);
- std::optional<int32_t> unhandledKeycode =
- getItemFromStorageLockedInterruptible(10ms, mReportedUnhandledKeycodes, lock,
- mNotifyUnhandledKey);
- ASSERT_FALSE(unhandledKeycode) << "Expected unhandled key NOT to be reported";
- }
-
-private:
- std::mutex mLock;
- std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
- std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
- sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
- std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
-
- std::condition_variable mPointerCaptureChangedCondition;
-
- std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
-
- // ANR handling
- std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
- std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
- std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
- std::condition_variable mNotifyAnr;
- std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
- std::condition_variable mNotifyInputChannelBroken;
-
- sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
- bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
-
- std::condition_variable mNotifyUserActivity;
- std::queue<UserActivityPokeEvent> mUserActivityPokeEvents;
-
- std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
-
- std::chrono::nanoseconds mStaleEventTimeout = 1000ms;
-
- BlockingQueue<std::pair<int32_t /*deviceId*/, std::set<gui::Uid>>> mNotifiedInteractions;
-
- std::condition_variable mNotifyUnhandledKey;
- std::queue<int32_t> mReportedUnhandledKeycodes GUARDED_BY(mLock);
- std::function<std::optional<KeyEvent>(const KeyEvent&)> mUnhandledKeyHandler GUARDED_BY(mLock);
-
- // All three ANR-related callbacks behave the same way, so we use this generic function to wait
- // for a specific container to become non-empty. When the container is non-empty, return the
- // first entry from the container and erase it.
- template <class T>
- T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
- std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
- // If there is an ANR, Dispatcher won't be idle because there are still events
- // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
- // before checking if ANR was called.
- // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
- // to provide it some time to act. 100ms seems reasonable.
- std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
- const std::chrono::time_point start = std::chrono::steady_clock::now();
- std::optional<T> token =
- getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
- if (!token.has_value()) {
- ADD_FAILURE() << "Did not receive the ANR callback";
- return {};
- }
-
- const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
- // Ensure that the ANR didn't get raised too early. We can't be too strict here because
- // the dispatcher started counting before this function was called
- if (std::chrono::abs(timeout - waited) > 100ms) {
- ADD_FAILURE() << "ANR was raised too early or too late. Expected "
- << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
- << "ms, but waited "
- << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
- << "ms instead";
- }
- return *token;
- }
-
- template <class T>
- std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
- std::queue<T>& storage,
- std::unique_lock<std::mutex>& lock,
- std::condition_variable& condition)
- REQUIRES(mLock) {
- condition.wait_for(lock, timeout,
- [&storage]() REQUIRES(mLock) { return !storage.empty(); });
- if (storage.empty()) {
- return std::nullopt;
- }
- T item = storage.front();
- storage.pop();
- return std::make_optional(item);
- }
-
- void notifyConfigurationChanged(nsecs_t when) override {
- std::scoped_lock lock(mLock);
- mConfigurationChangedTime = when;
- }
-
- void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<gui::Pid> pid,
- const std::string&) override {
- std::scoped_lock lock(mLock);
- mAnrWindows.push({connectionToken, pid});
- mNotifyAnr.notify_all();
- }
-
- void notifyWindowResponsive(const sp<IBinder>& connectionToken,
- std::optional<gui::Pid> pid) override {
- std::scoped_lock lock(mLock);
- mResponsiveWindows.push({connectionToken, pid});
- mNotifyAnr.notify_all();
- }
-
- void notifyNoFocusedWindowAnr(
- const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
- std::scoped_lock lock(mLock);
- mAnrApplications.push(applicationHandle);
- mNotifyAnr.notify_all();
- }
-
- void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
- std::scoped_lock lock(mLock);
- mBrokenInputChannels.push(connectionToken);
- mNotifyInputChannelBroken.notify_all();
- }
-
- void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
-
- void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
- InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
- const std::vector<float>& values) override {}
-
- void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
- InputDeviceSensorAccuracy accuracy) override {}
-
- void notifyVibratorState(int32_t deviceId, bool isOn) override {}
-
- bool filterInputEvent(const InputEvent& inputEvent, uint32_t policyFlags) override {
- std::scoped_lock lock(mLock);
- switch (inputEvent.getType()) {
- case InputEventType::KEY: {
- const KeyEvent& keyEvent = static_cast<const KeyEvent&>(inputEvent);
- mFilteredEvent = std::make_unique<KeyEvent>(keyEvent);
- break;
- }
-
- case InputEventType::MOTION: {
- const MotionEvent& motionEvent = static_cast<const MotionEvent&>(inputEvent);
- mFilteredEvent = std::make_unique<MotionEvent>(motionEvent);
- break;
- }
- default: {
- ADD_FAILURE() << "Should only filter keys or motions";
- break;
- }
- }
- return true;
- }
-
- void interceptKeyBeforeQueueing(const KeyEvent& inputEvent, uint32_t&) override {
- if (inputEvent.getAction() == AKEY_EVENT_ACTION_UP) {
- // Clear intercept state when we handled the event.
- mInterceptKeyTimeout = 0ms;
- }
- }
-
- void interceptMotionBeforeQueueing(int32_t, uint32_t, int32_t, nsecs_t, uint32_t&) override {}
-
- nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent&, uint32_t) override {
- nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
- // Clear intercept state so we could dispatch the event in next wake.
- mInterceptKeyTimeout = 0ms;
- return delay;
- }
-
- std::optional<KeyEvent> dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent& event,
- uint32_t) override {
- std::scoped_lock lock(mLock);
- mReportedUnhandledKeycodes.emplace(event.getKeyCode());
- mNotifyUnhandledKey.notify_all();
- return mUnhandledKeyHandler != nullptr ? mUnhandledKeyHandler(event) : std::nullopt;
- }
-
- void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
- uint32_t policyFlags) override {
- std::scoped_lock lock(mLock);
- /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
- * essentially a passthrough for notifySwitch.
- */
- mLastNotifySwitch =
- NotifySwitchArgs(InputEvent::nextId(), when, policyFlags, switchValues, switchMask);
- }
-
- void pokeUserActivity(nsecs_t eventTime, int32_t eventType, int32_t displayId) override {
- std::scoped_lock lock(mLock);
- mNotifyUserActivity.notify_all();
- mUserActivityPokeEvents.push({eventTime, eventType, displayId});
- }
-
- bool isStaleEvent(nsecs_t currentTime, nsecs_t eventTime) override {
- return std::chrono::nanoseconds(currentTime - eventTime) >= mStaleEventTimeout;
- }
-
- void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
- std::scoped_lock lock(mLock);
- mOnPointerDownToken = newToken;
- }
-
- void setPointerCapture(const PointerCaptureRequest& request) override {
- std::scoped_lock lock(mLock);
- mPointerCaptureRequest = {request};
- mPointerCaptureChangedCondition.notify_all();
- }
-
- void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
- std::scoped_lock lock(mLock);
- mNotifyDropWindowWasCalled = true;
- mDropTargetWindowToken = token;
- }
-
- void notifyDeviceInteraction(int32_t deviceId, nsecs_t timestamp,
- const std::set<gui::Uid>& uids) override {
- ASSERT_TRUE(mNotifiedInteractions.emplace(deviceId, uids));
- }
-
- void assertFilterInputEventWasCalledInternal(
- const std::function<void(const InputEvent&)>& verify) {
- std::scoped_lock lock(mLock);
- ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
- verify(*mFilteredEvent);
- mFilteredEvent = nullptr;
- }
-
- gui::Uid getPackageUid(std::string) override { return gui::Uid::INVALID; }
-};
} // namespace
// --- InputDispatcherTest ---