xref: /aosp_15_r20/frameworks/native/services/inputflinger/reader/include/InputReader.h (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
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 
17 #pragma once
18 
19 #include <android-base/thread_annotations.h>
20 #include <utils/Condition.h>
21 #include <utils/Mutex.h>
22 
23 #include <memory>
24 #include <unordered_map>
25 #include <vector>
26 
27 #include "EventHub.h"
28 #include "InputListener.h"
29 #include "InputReaderBase.h"
30 #include "InputReaderContext.h"
31 #include "InputThread.h"
32 
33 namespace android {
34 
35 class InputDevice;
36 class InputMapper;
37 struct StylusState;
38 
39 /* The input reader reads raw event data from the event hub and processes it into input events
40  * that it sends to the input listener.  Some functions of the input reader, such as early
41  * event filtering in low power states, are controlled by a separate policy object.
42  *
43  * The InputReader owns a collection of InputMappers. InputReader starts its own thread, where
44  * most of the work happens, but the InputReader can receive queries from other system
45  * components running on arbitrary threads.  To keep things manageable, the InputReader
46  * uses a single Mutex to guard its state.  The Mutex may be held while calling into the
47  * EventHub or the InputReaderPolicy but it is never held while calling into the
48  * InputListener. All calls to InputListener must happen from InputReader's thread.
49  */
50 class InputReader : public InputReaderInterface {
51 public:
52     InputReader(std::shared_ptr<EventHubInterface> eventHub,
53                 const sp<InputReaderPolicyInterface>& policy, InputListenerInterface& listener);
54     virtual ~InputReader();
55 
56     void dump(std::string& dump) override;
57     void monitor() override;
58 
59     status_t start() override;
60     status_t stop() override;
61 
62     std::vector<InputDeviceInfo> getInputDevices() const override;
63 
64     int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) override;
65     int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) override;
66     int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t sw) override;
67 
68     int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const override;
69 
70     void toggleCapsLockState(int32_t deviceId) override;
71 
72     void resetLockedModifierState() override;
73 
74     bool hasKeys(int32_t deviceId, uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
75                  uint8_t* outFlags) override;
76 
77     void requestRefreshConfiguration(ConfigurationChanges changes) override;
78 
79     void vibrate(int32_t deviceId, const VibrationSequence& sequence, ssize_t repeat,
80                  int32_t token) override;
81     void cancelVibrate(int32_t deviceId, int32_t token) override;
82 
83     bool isVibrating(int32_t deviceId) override;
84 
85     std::vector<int32_t> getVibratorIds(int32_t deviceId) override;
86 
87     bool canDispatchToDisplay(int32_t deviceId, ui::LogicalDisplayId displayId) override;
88 
89     bool enableSensor(int32_t deviceId, InputDeviceSensorType sensorType,
90                       std::chrono::microseconds samplingPeriod,
91                       std::chrono::microseconds maxBatchReportLatency) override;
92 
93     void disableSensor(int32_t deviceId, InputDeviceSensorType sensorType) override;
94 
95     void flushSensor(int32_t deviceId, InputDeviceSensorType sensorType) override;
96 
97     std::optional<int32_t> getBatteryCapacity(int32_t deviceId) override;
98 
99     std::optional<int32_t> getBatteryStatus(int32_t deviceId) override;
100 
101     std::optional<std::string> getBatteryDevicePath(int32_t deviceId) override;
102 
103     std::vector<InputDeviceLightInfo> getLights(int32_t deviceId) override;
104 
105     std::vector<InputDeviceSensorInfo> getSensors(int32_t deviceId) override;
106 
107     std::optional<HardwareProperties> getTouchpadHardwareProperties(int32_t deviceId) override;
108 
109     bool setLightColor(int32_t deviceId, int32_t lightId, int32_t color) override;
110 
111     bool setLightPlayerId(int32_t deviceId, int32_t lightId, int32_t playerId) override;
112 
113     std::optional<int32_t> getLightColor(int32_t deviceId, int32_t lightId) override;
114 
115     std::optional<int32_t> getLightPlayerId(int32_t deviceId, int32_t lightId) override;
116 
117     std::optional<std::string> getBluetoothAddress(int32_t deviceId) const override;
118 
119     void sysfsNodeChanged(const std::string& sysfsNodePath) override;
120 
121     DeviceId getLastUsedInputDeviceId() override;
122 
123     void notifyMouseCursorFadedOnTyping() override;
124 
125     bool setKernelWakeEnabled(int32_t deviceId, bool enabled) override;
126 
127 protected:
128     // These members are protected so they can be instrumented by test cases.
129     virtual std::shared_ptr<InputDevice> createDeviceLocked(nsecs_t when, int32_t deviceId,
130                                                             const InputDeviceIdentifier& identifier)
131             REQUIRES(mLock);
132 
133     // With each iteration of the loop, InputReader reads and processes one incoming message from
134     // the EventHub.
135     void loopOnce();
136 
137     class ContextImpl : public InputReaderContext {
138         InputReader* mReader;
139         IdGenerator mIdGenerator;
140 
141     public:
142         explicit ContextImpl(InputReader* reader);
143         // lock is already held by the input loop
144         void updateGlobalMetaState() NO_THREAD_SAFETY_ANALYSIS override;
145         int32_t getGlobalMetaState() NO_THREAD_SAFETY_ANALYSIS override;
146         void disableVirtualKeysUntil(nsecs_t time) REQUIRES(mReader->mLock) override;
147         bool shouldDropVirtualKey(nsecs_t now, int32_t keyCode, int32_t scanCode)
148                 REQUIRES(mReader->mLock) override;
149         void requestTimeoutAtTime(nsecs_t when) REQUIRES(mReader->mLock) override;
150         int32_t bumpGeneration() NO_THREAD_SAFETY_ANALYSIS override;
151         void getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices)
152                 REQUIRES(mReader->mLock) override;
153         [[nodiscard]] std::list<NotifyArgs> dispatchExternalStylusState(const StylusState& outState)
154                 REQUIRES(mReader->mLock) override;
155         InputReaderPolicyInterface* getPolicy() REQUIRES(mReader->mLock) override;
156         EventHubInterface* getEventHub() REQUIRES(mReader->mLock) override;
157         int32_t getNextId() NO_THREAD_SAFETY_ANALYSIS override;
158         void updateLedMetaState(int32_t metaState) REQUIRES(mReader->mLock) override;
159         int32_t getLedMetaState() REQUIRES(mReader->mLock) REQUIRES(mLock) override;
160         void setPreventingTouchpadTaps(bool prevent) REQUIRES(mReader->mLock)
161                 REQUIRES(mLock) override;
162         bool isPreventingTouchpadTaps() REQUIRES(mReader->mLock) REQUIRES(mLock) override;
163         void setLastKeyDownTimestamp(nsecs_t when) REQUIRES(mReader->mLock)
164                 REQUIRES(mLock) override;
165         nsecs_t getLastKeyDownTimestamp() REQUIRES(mReader->mLock) REQUIRES(mLock) override;
166         KeyboardClassifier& getKeyboardClassifier() override;
167     } mContext;
168 
169     friend class ContextImpl;
170     // Test cases need to override the locked functions
171     mutable std::mutex mLock;
172 
173 private:
174     std::unique_ptr<InputThread> mThread;
175 
176     std::condition_variable mReaderIsAliveCondition;
177 
178     // This could be unique_ptr, but due to the way InputReader tests are written,
179     // it is made shared_ptr here. In the tests, an EventHub reference is retained by the test
180     // in parallel to passing it to the InputReader.
181     std::shared_ptr<EventHubInterface> mEventHub;
182     sp<InputReaderPolicyInterface> mPolicy;
183 
184     // The next stage that should receive the events generated inside InputReader.
185     InputListenerInterface& mNextListener;
186 
187     // Classifier for keyboard/keyboard-like devices
188     std::unique_ptr<KeyboardClassifier> mKeyboardClassifier;
189 
190     // As various events are generated inside InputReader, they are stored inside this list. The
191     // list can only be accessed with the lock, so the events inside it are well-ordered.
192     // Once the reader is done working, these events will be swapped into a temporary storage and
193     // sent to the 'mNextListener' without holding the lock.
194     std::list<NotifyArgs> mPendingArgs GUARDED_BY(mLock);
195 
196     InputReaderConfiguration mConfig GUARDED_BY(mLock);
197 
198     // An input device can represent a collection of EventHub devices. This map provides a way
199     // to lookup the input device instance from the EventHub device id.
200     std::unordered_map<int32_t /*eventHubId*/, std::shared_ptr<InputDevice>> mDevices
201             GUARDED_BY(mLock);
202 
203     // An input device contains one or more eventHubId, this map provides a way to lookup the
204     // EventHubIds contained in the input device from the input device instance.
205     std::unordered_map<std::shared_ptr<InputDevice>, std::vector<int32_t> /*eventHubId*/>
206             mDeviceToEventHubIdsMap GUARDED_BY(mLock);
207 
208     // true if tap-to-click on touchpad is currently disabled
GUARDED_BY(mLock)209     bool mPreventingTouchpadTaps GUARDED_BY(mLock){false};
210 
211     // records timestamp of the last key press on the physical keyboard
GUARDED_BY(mLock)212     nsecs_t mLastKeyDownTimestamp GUARDED_BY(mLock){0};
213 
214     // The input device that produced a new gesture most recently.
GUARDED_BY(mLock)215     DeviceId mLastUsedDeviceId GUARDED_BY(mLock){ReservedInputDeviceId::INVALID_INPUT_DEVICE_ID};
216 
217     // low-level input event decoding and device management
218     [[nodiscard]] std::list<NotifyArgs> processEventsLocked(const RawEvent* rawEvents, size_t count)
219             REQUIRES(mLock);
220 
221     void addDeviceLocked(nsecs_t when, int32_t eventHubId) REQUIRES(mLock);
222     void removeDeviceLocked(nsecs_t when, int32_t eventHubId) REQUIRES(mLock);
223     [[nodiscard]] std::list<NotifyArgs> processEventsForDeviceLocked(int32_t eventHubId,
224                                                                      const RawEvent* rawEvents,
225                                                                      size_t count) REQUIRES(mLock);
226     [[nodiscard]] std::list<NotifyArgs> timeoutExpiredLocked(nsecs_t when) REQUIRES(mLock);
227 
228     int32_t mGlobalMetaState GUARDED_BY(mLock);
229     void updateGlobalMetaStateLocked() REQUIRES(mLock);
230     int32_t getGlobalMetaStateLocked() REQUIRES(mLock);
231 
232     int32_t mLedMetaState GUARDED_BY(mLock);
233     void updateLedMetaStateLocked(int32_t metaState) REQUIRES(mLock);
234     int32_t getLedMetaStateLocked() REQUIRES(mLock);
235 
236     void notifyExternalStylusPresenceChangedLocked() REQUIRES(mLock);
237     void getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) REQUIRES(mLock);
238     [[nodiscard]] std::list<NotifyArgs> dispatchExternalStylusStateLocked(const StylusState& state)
239             REQUIRES(mLock);
240 
241     int32_t mGeneration GUARDED_BY(mLock);
242     int32_t bumpGenerationLocked() REQUIRES(mLock);
243 
244     int32_t mNextInputDeviceId GUARDED_BY(mLock);
245     int32_t nextInputDeviceIdLocked() REQUIRES(mLock);
246 
247     std::vector<InputDeviceInfo> getInputDevicesLocked() const REQUIRES(mLock);
248 
249     nsecs_t mDisableVirtualKeysTimeout GUARDED_BY(mLock);
250     void disableVirtualKeysUntilLocked(nsecs_t time) REQUIRES(mLock);
251     bool shouldDropVirtualKeyLocked(nsecs_t now, int32_t keyCode, int32_t scanCode) REQUIRES(mLock);
252 
253     nsecs_t mNextTimeout GUARDED_BY(mLock);
254     void requestTimeoutAtTimeLocked(nsecs_t when) REQUIRES(mLock);
255 
256     ConfigurationChanges mConfigurationChangesToRefresh GUARDED_BY(mLock);
257     void refreshConfigurationLocked(ConfigurationChanges changes) REQUIRES(mLock);
258 
259     PointerCaptureRequest mCurrentPointerCaptureRequest GUARDED_BY(mLock);
260 
261     // state queries
262     typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
263     int32_t getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
264                            GetStateFunc getStateFunc) REQUIRES(mLock);
265     bool markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
266                                      const std::vector<int32_t>& keyCodes, uint8_t* outFlags)
267             REQUIRES(mLock);
268 
269     // find an InputDevice from an InputDevice id
270     InputDevice* findInputDeviceLocked(int32_t deviceId) const REQUIRES(mLock);
271 };
272 
273 } // namespace android
274