• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 assertNotifyConfigurationChangedWasCalled(nsecs_t when);
70     void assertNotifySwitchWasCalled(const NotifySwitchArgs& args);
71     void assertOnPointerDownEquals(const sp<IBinder>& touchedToken);
72     void assertOnPointerDownWasNotCalled();
73     /**
74      * This function must be called soon after the expected ANR timer starts,
75      * because we are also checking how much time has passed.
76      */
77     void assertNotifyNoFocusedWindowAnrWasCalled(
78             std::chrono::nanoseconds timeout,
79             const std::shared_ptr<InputApplicationHandle>& expectedApplication);
80     void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
81                                                  const sp<gui::WindowInfoHandle>& window);
82     void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
83                                                  const sp<IBinder>& expectedToken,
84                                                  std::optional<gui::Pid> expectedPid);
85     /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
86     sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout);
87     void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
88                                                std::optional<gui::Pid> expectedPid);
89     /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
90     sp<IBinder> getResponsiveWindowToken();
91     void assertNotifyAnrWasNotCalled();
92     PointerCaptureRequest assertSetPointerCaptureCalled(const sp<gui::WindowInfoHandle>& window,
93                                                         bool enabled);
94     void assertSetPointerCaptureNotCalled();
95     void assertDropTargetEquals(const InputDispatcherInterface& dispatcher,
96                                 const sp<IBinder>& targetToken);
97     void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token);
98     /**
99      * Set policy timeout. A value of zero means next key will not be intercepted.
100      */
101     void setInterceptKeyTimeout(std::chrono::milliseconds timeout);
102     std::chrono::nanoseconds getKeyWaitingForEventsTimeout() override;
103     void setStaleEventTimeout(std::chrono::nanoseconds timeout);
104     void assertUserActivityNotPoked();
105     /**
106      * Asserts that a user activity poke has happened. The earliest recorded poke event will be
107      * cleared after this call.
108      *
109      * If an expected UserActivityPokeEvent is provided, asserts that the given event is the
110      * earliest recorded poke event.
111      */
112     void assertUserActivityPoked(std::optional<UserActivityPokeEvent> expectedPokeEvent = {});
113     void assertNotifyDeviceInteractionWasCalled(int32_t deviceId, std::set<gui::Uid> uids);
114     void assertNotifyDeviceInteractionWasNotCalled();
115     void setUnhandledKeyHandler(std::function<std::optional<KeyEvent>(const KeyEvent&)> handler);
116     void assertUnhandledKeyReported(int32_t keycode);
117     void assertUnhandledKeyNotReported();
118     void setConsumeKeyBeforeDispatching(bool consumeKeyBeforeDispatching);
119     void assertFocusedDisplayNotified(ui::LogicalDisplayId expectedDisplay);
120 
121 private:
122     std::mutex mLock;
123     std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
124     std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
125     sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
126     std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
127 
128     std::condition_variable mPointerCaptureChangedCondition;
129 
130     std::optional<ui::LogicalDisplayId> mNotifiedFocusedDisplay GUARDED_BY(mLock);
131     std::condition_variable mFocusedDisplayNotifiedCondition;
132 
133     std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
134     // ANR handling
135     std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
136     std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
137     std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
138     std::condition_variable mNotifyAnr;
139     std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
140     std::condition_variable mNotifyInputChannelBroken;
141 
142     sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
143     bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
144 
145     std::condition_variable mNotifyUserActivity;
146     std::queue<UserActivityPokeEvent> mUserActivityPokeEvents;
147 
148     std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
149 
150     std::chrono::nanoseconds mStaleEventTimeout = 1000ms;
151 
152     bool mConsumeKeyBeforeDispatching = false;
153 
154     BlockingQueue<std::pair<int32_t /*deviceId*/, std::set<gui::Uid>>> mNotifiedInteractions;
155 
156     std::condition_variable mNotifyUnhandledKey;
157     std::queue<int32_t> mReportedUnhandledKeycodes GUARDED_BY(mLock);
158     std::function<std::optional<KeyEvent>(const KeyEvent&)> mUnhandledKeyHandler GUARDED_BY(mLock);
159 
160     /**
161      * All three ANR-related callbacks behave the same way, so we use this generic function to wait
162      * for a specific container to become non-empty. When the container is non-empty, return the
163      * first entry from the container and erase it.
164      */
165     template <class T>
166     T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
167                                      std::unique_lock<std::mutex>& lock) REQUIRES(mLock);
168 
169     template <class T>
170     std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
171                                                            std::queue<T>& storage,
172                                                            std::unique_lock<std::mutex>& lock,
173                                                            std::condition_variable& condition)
174             REQUIRES(mLock);
175 
176     void notifyConfigurationChanged(nsecs_t when) override;
177     void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<gui::Pid> pid,
178                                   const std::string&) override;
179     void notifyWindowResponsive(const sp<IBinder>& connectionToken,
180                                 std::optional<gui::Pid> pid) override;
181     void notifyNoFocusedWindowAnr(
182             const std::shared_ptr<InputApplicationHandle>& applicationHandle) override;
183     void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override;
184     void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override;
185     void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
186                            InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
187                            const std::vector<float>& values) override;
188     void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
189                               InputDeviceSensorAccuracy accuracy) override;
190     void notifyVibratorState(int32_t deviceId, bool isOn) override;
191     bool filterInputEvent(const InputEvent& inputEvent, uint32_t policyFlags) override;
192     void interceptKeyBeforeQueueing(const KeyEvent& inputEvent, uint32_t&) override;
193     void interceptMotionBeforeQueueing(ui::LogicalDisplayId, uint32_t, int32_t, nsecs_t,
194                                        uint32_t&) override;
195     nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent&, uint32_t) override;
196     std::optional<KeyEvent> dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent& event,
197                                                  uint32_t) override;
198     void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
199                       uint32_t policyFlags) override;
200     void pokeUserActivity(nsecs_t eventTime, int32_t eventType,
201                           ui::LogicalDisplayId displayId) override;
202     bool isStaleEvent(nsecs_t currentTime, nsecs_t eventTime) override;
203     void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override;
204     void setPointerCapture(const PointerCaptureRequest& request) override;
205     void notifyDropWindow(const sp<IBinder>& token, float x, float y) override;
206     void notifyDeviceInteraction(int32_t deviceId, nsecs_t timestamp,
207                                  const std::set<gui::Uid>& uids) override;
208     void notifyFocusedDisplayChanged(ui::LogicalDisplayId displayId) override;
209 
210     void assertFilterInputEventWasCalledInternal(
211             const std::function<void(const InputEvent&)>& verify);
212 };
213 
214 } // namespace android
215