xref: /aosp_15_r20/frameworks/native/services/inputflinger/tests/FakeInputDispatcherPolicy.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright 2023 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 
17 #pragma once
18 
19 #include "InputDispatcherPolicyInterface.h"
20 
21 #include "InputDispatcherInterface.h"
22 #include "NotifyArgs.h"
23 
24 #include <condition_variable>
25 #include <functional>
26 #include <memory>
27 #include <mutex>
28 #include <optional>
29 #include <queue>
30 #include <string>
31 #include <vector>
32 
33 #include <android-base/logging.h>
34 #include <android-base/thread_annotations.h>
35 #include <binder/IBinder.h>
36 #include <gui/PidUid.h>
37 #include <gui/WindowInfo.h>
38 #include <input/BlockingQueue.h>
39 #include <input/Input.h>
40 
41 namespace android {
42 
43 class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
44 public:
45     FakeInputDispatcherPolicy() = default;
46     virtual ~FakeInputDispatcherPolicy() = default;
47 
48     struct AnrResult {
49         sp<IBinder> token{};
50         std::optional<gui::Pid> pid{};
51     };
52 
53     struct UserActivityPokeEvent {
54         nsecs_t eventTime;
55         int32_t eventType;
56         ui::LogicalDisplayId displayId;
57 
58         bool operator==(const UserActivityPokeEvent& rhs) const = default;
59         inline friend std::ostream& operator<<(std::ostream& os, const UserActivityPokeEvent& ev) {
60             os << "UserActivityPokeEvent[time=" << ev.eventTime << ", eventType=" << ev.eventType
61                << ", displayId=" << ev.displayId << "]";
62             return os;
63         }
64     };
65 
66     void assertFilterInputEventWasCalled(const NotifyKeyArgs& args);
67     void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point);
68     void assertFilterInputEventWasNotCalled();
69     void assertNotifySwitchWasCalled(const NotifySwitchArgs& args);
70     void assertOnPointerDownEquals(const sp<IBinder>& touchedToken);
71     void assertOnPointerDownWasNotCalled();
72     /**
73      * This function must be called soon after the expected ANR timer starts,
74      * because we are also checking how much time has passed.
75      */
76     void assertNotifyNoFocusedWindowAnrWasCalled(
77             std::chrono::nanoseconds timeout,
78             const std::shared_ptr<InputApplicationHandle>& expectedApplication);
79     void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
80                                                  const sp<gui::WindowInfoHandle>& window);
81     void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
82                                                  const sp<IBinder>& expectedToken,
83                                                  std::optional<gui::Pid> expectedPid);
84     /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
85     sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout);
86     void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
87                                                std::optional<gui::Pid> expectedPid);
88     /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
89     sp<IBinder> getResponsiveWindowToken();
90     void assertNotifyAnrWasNotCalled();
91     PointerCaptureRequest assertSetPointerCaptureCalled(const sp<gui::WindowInfoHandle>& window,
92                                                         bool enabled);
93     void assertSetPointerCaptureNotCalled();
94     void assertDropTargetEquals(const InputDispatcherInterface& dispatcher,
95                                 const sp<IBinder>& targetToken);
96     void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token);
97     /**
98      * Set policy timeout. A value of zero means next key will not be intercepted.
99      */
100     void setInterceptKeyTimeout(std::chrono::milliseconds timeout);
101     std::chrono::nanoseconds getKeyWaitingForEventsTimeout() override;
102     void setStaleEventTimeout(std::chrono::nanoseconds timeout);
103     void assertUserActivityNotPoked();
104     /**
105      * Asserts that a user activity poke has happened. The earliest recorded poke event will be
106      * cleared after this call.
107      *
108      * If an expected UserActivityPokeEvent is provided, asserts that the given event is the
109      * earliest recorded poke event.
110      */
111     void assertUserActivityPoked(std::optional<UserActivityPokeEvent> expectedPokeEvent = {});
112     void assertNotifyDeviceInteractionWasCalled(int32_t deviceId, std::set<gui::Uid> uids);
113     void assertNotifyDeviceInteractionWasNotCalled();
114     void setUnhandledKeyHandler(std::function<std::optional<KeyEvent>(const KeyEvent&)> handler);
115     void assertUnhandledKeyReported(int32_t keycode);
116     void assertUnhandledKeyNotReported();
117     void setConsumeKeyBeforeDispatching(bool consumeKeyBeforeDispatching);
118     void assertFocusedDisplayNotified(ui::LogicalDisplayId expectedDisplay);
119 
120 private:
121     std::mutex mLock;
122     std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
123     sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
124     std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
125 
126     std::condition_variable mPointerCaptureChangedCondition;
127 
128     std::optional<ui::LogicalDisplayId> mNotifiedFocusedDisplay GUARDED_BY(mLock);
129     std::condition_variable mFocusedDisplayNotifiedCondition;
130 
131     std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
132     // ANR handling
133     std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
134     std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
135     std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
136     std::condition_variable mNotifyAnr;
137     std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
138     std::condition_variable mNotifyInputChannelBroken;
139 
140     sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
141     bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
142 
143     std::condition_variable mNotifyUserActivity;
144     std::queue<UserActivityPokeEvent> mUserActivityPokeEvents;
145 
146     std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
147 
148     std::chrono::nanoseconds mStaleEventTimeout = 1000ms;
149 
150     bool mConsumeKeyBeforeDispatching = false;
151 
152     BlockingQueue<std::pair<int32_t /*deviceId*/, std::set<gui::Uid>>> mNotifiedInteractions;
153 
154     std::condition_variable mNotifyUnhandledKey;
155     std::queue<int32_t> mReportedUnhandledKeycodes GUARDED_BY(mLock);
156     std::function<std::optional<KeyEvent>(const KeyEvent&)> mUnhandledKeyHandler GUARDED_BY(mLock);
157 
158     /**
159      * All three ANR-related callbacks behave the same way, so we use this generic function to wait
160      * for a specific container to become non-empty. When the container is non-empty, return the
161      * first entry from the container and erase it.
162      */
163     template <class T>
164     T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
165                                      std::unique_lock<std::mutex>& lock) REQUIRES(mLock);
166 
167     template <class T>
168     std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
169                                                            std::queue<T>& storage,
170                                                            std::unique_lock<std::mutex>& lock,
171                                                            std::condition_variable& condition)
172             REQUIRES(mLock);
173 
174     void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<gui::Pid> pid,
175                                   const std::string&) override;
176     void notifyWindowResponsive(const sp<IBinder>& connectionToken,
177                                 std::optional<gui::Pid> pid) override;
178     void notifyNoFocusedWindowAnr(
179             const std::shared_ptr<InputApplicationHandle>& applicationHandle) override;
180     void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override;
181     void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override;
182     void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
183                            InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
184                            const std::vector<float>& values) override;
185     void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
186                               InputDeviceSensorAccuracy accuracy) override;
187     void notifyVibratorState(int32_t deviceId, bool isOn) override;
188     bool filterInputEvent(const InputEvent& inputEvent, uint32_t policyFlags) override;
189     void interceptKeyBeforeQueueing(const KeyEvent& inputEvent, uint32_t&) override;
190     void interceptMotionBeforeQueueing(ui::LogicalDisplayId, uint32_t, int32_t, nsecs_t,
191                                        uint32_t&) override;
192     nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent&, uint32_t) override;
193     std::optional<KeyEvent> dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent& event,
194                                                  uint32_t) override;
195     void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
196                       uint32_t policyFlags) override;
197     void pokeUserActivity(nsecs_t eventTime, int32_t eventType,
198                           ui::LogicalDisplayId displayId) override;
199     bool isStaleEvent(nsecs_t currentTime, nsecs_t eventTime) override;
200     void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override;
201     void setPointerCapture(const PointerCaptureRequest& request) override;
202     void notifyDropWindow(const sp<IBinder>& token, float x, float y) override;
203     void notifyDeviceInteraction(int32_t deviceId, nsecs_t timestamp,
204                                  const std::set<gui::Uid>& uids) override;
205     void notifyFocusedDisplayChanged(ui::LogicalDisplayId displayId) override;
206 
207     void assertFilterInputEventWasCalledInternal(
208             const std::function<void(const InputEvent&)>& verify);
209 };
210 
211 } // namespace android
212