• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2005 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 #ifndef _RUNTIME_EVENT_HUB_H
18 #define _RUNTIME_EVENT_HUB_H
19 
20 #include <bitset>
21 #include <climits>
22 #include <unordered_map>
23 #include <vector>
24 
25 #include <input/Flags.h>
26 #include <filesystem>
27 
28 #include <batteryservice/BatteryService.h>
29 #include <input/Input.h>
30 #include <input/InputDevice.h>
31 #include <input/KeyCharacterMap.h>
32 #include <input/KeyLayoutMap.h>
33 #include <input/Keyboard.h>
34 #include <input/PropertyMap.h>
35 #include <input/VirtualKeyMap.h>
36 #include <linux/input.h>
37 #include <sys/epoll.h>
38 #include <utils/BitSet.h>
39 #include <utils/Errors.h>
40 #include <utils/KeyedVector.h>
41 #include <utils/List.h>
42 #include <utils/Log.h>
43 #include <utils/Mutex.h>
44 
45 #include "TouchVideoDevice.h"
46 #include "VibrationElement.h"
47 
48 namespace android {
49 
50 /* Number of colors : {red, green, blue} */
51 static constexpr size_t COLOR_NUM = 3;
52 /*
53  * A raw event as retrieved from the EventHub.
54  */
55 struct RawEvent {
56     // Time when the event happened
57     nsecs_t when;
58     // Time when the event was read by EventHub. Only populated for input events.
59     // For other events (device added/removed/etc), this value is undefined and should not be read.
60     nsecs_t readTime;
61     int32_t deviceId;
62     int32_t type;
63     int32_t code;
64     int32_t value;
65 };
66 
67 /* Describes an absolute axis. */
68 struct RawAbsoluteAxisInfo {
69     bool valid; // true if the information is valid, false otherwise
70 
71     int32_t minValue;   // minimum value
72     int32_t maxValue;   // maximum value
73     int32_t flat;       // center flat position, eg. flat == 8 means center is between -8 and 8
74     int32_t fuzz;       // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise
75     int32_t resolution; // resolution in units per mm or radians per mm
76 
clearRawAbsoluteAxisInfo77     inline void clear() {
78         valid = false;
79         minValue = 0;
80         maxValue = 0;
81         flat = 0;
82         fuzz = 0;
83         resolution = 0;
84     }
85 };
86 
87 /*
88  * Input device classes.
89  */
90 enum class InputDeviceClass : uint32_t {
91     /* The input device is a keyboard or has buttons. */
92     KEYBOARD = 0x00000001,
93 
94     /* The input device is an alpha-numeric keyboard (not just a dial pad). */
95     ALPHAKEY = 0x00000002,
96 
97     /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */
98     TOUCH = 0x00000004,
99 
100     /* The input device is a cursor device such as a trackball or mouse. */
101     CURSOR = 0x00000008,
102 
103     /* The input device is a multi-touch touchscreen. */
104     TOUCH_MT = 0x00000010,
105 
106     /* The input device is a directional pad (implies keyboard, has DPAD keys). */
107     DPAD = 0x00000020,
108 
109     /* The input device is a gamepad (implies keyboard, has BUTTON keys). */
110     GAMEPAD = 0x00000040,
111 
112     /* The input device has switches. */
113     SWITCH = 0x00000080,
114 
115     /* The input device is a joystick (implies gamepad, has joystick absolute axes). */
116     JOYSTICK = 0x00000100,
117 
118     /* The input device has a vibrator (supports FF_RUMBLE). */
119     VIBRATOR = 0x00000200,
120 
121     /* The input device has a microphone. */
122     MIC = 0x00000400,
123 
124     /* The input device is an external stylus (has data we want to fuse with touch data). */
125     EXTERNAL_STYLUS = 0x00000800,
126 
127     /* The input device has a rotary encoder */
128     ROTARY_ENCODER = 0x00001000,
129 
130     /* The input device has a sensor like accelerometer, gyro, etc */
131     SENSOR = 0x00002000,
132 
133     /* The input device has a battery */
134     BATTERY = 0x00004000,
135 
136     /* The input device has sysfs controllable lights */
137     LIGHT = 0x00008000,
138 
139     /* The input device is virtual (not a real device, not part of UI configuration). */
140     VIRTUAL = 0x40000000,
141 
142     /* The input device is external (not built-in). */
143     EXTERNAL = 0x80000000,
144 };
145 
146 enum class SysfsClass : uint32_t {
147     POWER_SUPPLY = 0,
148     LEDS = 1,
149 };
150 
151 enum class LightColor : uint32_t {
152     RED = 0,
153     GREEN = 1,
154     BLUE = 2,
155 };
156 
157 enum class InputLightClass : uint32_t {
158     /* The input light has brightness node. */
159     BRIGHTNESS = 0x00000001,
160     /* The input light has red name. */
161     RED = 0x00000002,
162     /* The input light has green name. */
163     GREEN = 0x00000004,
164     /* The input light has blue name. */
165     BLUE = 0x00000008,
166     /* The input light has global name. */
167     GLOBAL = 0x00000010,
168     /* The input light has multi index node. */
169     MULTI_INDEX = 0x00000020,
170     /* The input light has multi intensity node. */
171     MULTI_INTENSITY = 0x00000040,
172     /* The input light has max brightness node. */
173     MAX_BRIGHTNESS = 0x00000080,
174 };
175 
176 enum class InputBatteryClass : uint32_t {
177     /* The input device battery has capacity node. */
178     CAPACITY = 0x00000001,
179     /* The input device battery has capacity_level node. */
180     CAPACITY_LEVEL = 0x00000002,
181     /* The input device battery has status node. */
182     STATUS = 0x00000004,
183 };
184 
185 /* Describes a raw light. */
186 struct RawLightInfo {
187     int32_t id;
188     std::string name;
189     std::optional<int32_t> maxBrightness;
190     Flags<InputLightClass> flags;
191     std::array<int32_t, COLOR_NUM> rgbIndex;
192     std::filesystem::path path;
193 };
194 
195 /* Describes a raw battery. */
196 struct RawBatteryInfo {
197     int32_t id;
198     std::string name;
199     Flags<InputBatteryClass> flags;
200     std::filesystem::path path;
201 };
202 
203 /*
204  * Gets the class that owns an axis, in cases where multiple classes might claim
205  * the same axis for different purposes.
206  */
207 extern Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses);
208 
209 /*
210  * Grand Central Station for events.
211  *
212  * The event hub aggregates input events received across all known input
213  * devices on the system, including devices that may be emulated by the simulator
214  * environment.  In addition, the event hub generates fake input events to indicate
215  * when devices are added or removed.
216  *
217  * The event hub provides a stream of input events (via the getEvent function).
218  * It also supports querying the current actual state of input devices such as identifying
219  * which keys are currently down.  Finally, the event hub keeps track of the capabilities of
220  * individual input devices, such as their class and the set of key codes that they support.
221  */
222 class EventHubInterface {
223 public:
EventHubInterface()224     EventHubInterface() {}
~EventHubInterface()225     virtual ~EventHubInterface() {}
226 
227     // Synthetic raw event type codes produced when devices are added or removed.
228     enum {
229         // Sent when a device is added.
230         DEVICE_ADDED = 0x10000000,
231         // Sent when a device is removed.
232         DEVICE_REMOVED = 0x20000000,
233         // Sent when all added/removed devices from the most recent scan have been reported.
234         // This event is always sent at least once.
235         FINISHED_DEVICE_SCAN = 0x30000000,
236 
237         FIRST_SYNTHETIC_EVENT = DEVICE_ADDED,
238     };
239 
240     virtual Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const = 0;
241 
242     virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0;
243 
244     virtual int32_t getDeviceControllerNumber(int32_t deviceId) const = 0;
245 
246     virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0;
247 
248     virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
249                                          RawAbsoluteAxisInfo* outAxisInfo) const = 0;
250 
251     virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0;
252 
253     virtual bool hasInputProperty(int32_t deviceId, int property) const = 0;
254 
255     virtual bool hasMscEvent(int32_t deviceId, int mscEvent) const = 0;
256 
257     virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
258                             int32_t metaState, int32_t* outKeycode, int32_t* outMetaState,
259                             uint32_t* outFlags) const = 0;
260 
261     virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const = 0;
262 
263     // Sets devices that are excluded from opening.
264     // This can be used to ignore input devices for sensors.
265     virtual void setExcludedDevices(const std::vector<std::string>& devices) = 0;
266 
267     /*
268      * Wait for events to become available and returns them.
269      * After returning, the EventHub holds onto a wake lock until the next call to getEvent.
270      * This ensures that the device will not go to sleep while the event is being processed.
271      * If the device needs to remain awake longer than that, then the caller is responsible
272      * for taking care of it (say, by poking the power manager user activity timer).
273      *
274      * The timeout is advisory only.  If the device is asleep, it will not wake just to
275      * service the timeout.
276      *
277      * Returns the number of events obtained, or 0 if the timeout expired.
278      */
279     virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0;
280     virtual std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) = 0;
281     virtual base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor(int32_t deviceId,
282                                                                               int32_t absCode) = 0;
283     // Raw batteries are sysfs power_supply nodes we found from the EventHub device sysfs node,
284     // containing the raw info of the sysfs node structure.
285     virtual const std::vector<int32_t> getRawBatteryIds(int32_t deviceId) = 0;
286     virtual std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId,
287                                                             int32_t BatteryId) = 0;
288 
289     // Raw lights are sysfs led light nodes we found from the EventHub device sysfs node,
290     // containing the raw info of the sysfs node structure.
291     virtual const std::vector<int32_t> getRawLightIds(int32_t deviceId) = 0;
292     virtual std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, int32_t lightId) = 0;
293     virtual std::optional<int32_t> getLightBrightness(int32_t deviceId, int32_t lightId) = 0;
294     virtual void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) = 0;
295     virtual std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities(
296             int32_t deviceId, int32_t lightId) = 0;
297     virtual void setLightIntensities(int32_t deviceId, int32_t lightId,
298                                      std::unordered_map<LightColor, int32_t> intensities) = 0;
299     /*
300      * Query current input state.
301      */
302     virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0;
303     virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0;
304     virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0;
305     virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
306                                           int32_t* outValue) const = 0;
307 
308     /*
309      * Examine key input devices for specific framework keycode support
310      */
311     virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
312                                        uint8_t* outFlags) const = 0;
313 
314     virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0;
315 
316     /* LED related functions expect Android LED constants, not scan codes or HID usages */
317     virtual bool hasLed(int32_t deviceId, int32_t led) const = 0;
318     virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0;
319 
320     virtual void getVirtualKeyDefinitions(
321             int32_t deviceId, std::vector<VirtualKeyDefinition>& outVirtualKeys) const = 0;
322 
323     virtual const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0;
324     virtual bool setKeyboardLayoutOverlay(int32_t deviceId,
325                                           std::shared_ptr<KeyCharacterMap> map) = 0;
326 
327     /* Control the vibrator. */
328     virtual void vibrate(int32_t deviceId, const VibrationElement& effect) = 0;
329     virtual void cancelVibrate(int32_t deviceId) = 0;
330     virtual std::vector<int32_t> getVibratorIds(int32_t deviceId) = 0;
331 
332     /* Query battery level. */
333     virtual std::optional<int32_t> getBatteryCapacity(int32_t deviceId,
334                                                       int32_t batteryId) const = 0;
335 
336     /* Query battery status. */
337     virtual std::optional<int32_t> getBatteryStatus(int32_t deviceId, int32_t batteryId) const = 0;
338 
339     /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */
340     virtual void requestReopenDevices() = 0;
341 
342     /* Wakes up getEvents() if it is blocked on a read. */
343     virtual void wake() = 0;
344 
345     /* Dump EventHub state to a string. */
346     virtual void dump(std::string& dump) = 0;
347 
348     /* Called by the heatbeat to ensures that the reader has not deadlocked. */
349     virtual void monitor() = 0;
350 
351     /* Return true if the device is enabled. */
352     virtual bool isDeviceEnabled(int32_t deviceId) = 0;
353 
354     /* Enable an input device */
355     virtual status_t enableDevice(int32_t deviceId) = 0;
356 
357     /* Disable an input device. Closes file descriptor to that device. */
358     virtual status_t disableDevice(int32_t deviceId) = 0;
359 };
360 
361 template <std::size_t BITS>
362 class BitArray {
363     /* Array element type and vector of element type. */
364     using Element = std::uint32_t;
365     /* Number of bits in each BitArray element. */
366     static constexpr size_t WIDTH = sizeof(Element) * CHAR_BIT;
367     /* Number of elements to represent a bit array of the specified size of bits. */
368     static constexpr size_t COUNT = (BITS + WIDTH - 1) / WIDTH;
369 
370 public:
371     /* BUFFER type declaration for BitArray */
372     using Buffer = std::array<Element, COUNT>;
373     /* To tell if a bit is set in array, it selects an element from the array, and test
374      * if the relevant bit set.
375      * Note the parameter "bit" is an index to the bit, 0 <= bit < BITS.
376      */
test(size_t bit)377     inline bool test(size_t bit) const {
378         return (bit < BITS) ? mData[bit / WIDTH].test(bit % WIDTH) : false;
379     }
380     /* Returns total number of bytes needed for the array */
bytes()381     inline size_t bytes() { return (BITS + CHAR_BIT - 1) / CHAR_BIT; }
382     /* Returns true if array contains any non-zero bit from the range defined by start and end
383      * bit index [startIndex, endIndex).
384      */
any(size_t startIndex,size_t endIndex)385     bool any(size_t startIndex, size_t endIndex) {
386         if (startIndex >= endIndex || startIndex > BITS || endIndex > BITS + 1) {
387             ALOGE("Invalid start/end index. start = %zu, end = %zu, total bits = %zu", startIndex,
388                   endIndex, BITS);
389             return false;
390         }
391         size_t se = startIndex / WIDTH; // Start of element
392         size_t ee = endIndex / WIDTH;   // End of element
393         size_t si = startIndex % WIDTH; // Start index in start element
394         size_t ei = endIndex % WIDTH;   // End index in end element
395         // Need to check first unaligned bitset for any non zero bit
396         if (si > 0) {
397             size_t nBits = se == ee ? ei - si : WIDTH - si;
398             // Generate the mask of interested bit range
399             Element mask = ((1 << nBits) - 1) << si;
400             if (mData[se++].to_ulong() & mask) {
401                 return true;
402             }
403         }
404         // Check whole bitset for any bit set
405         for (; se < ee; se++) {
406             if (mData[se].any()) {
407                 return true;
408             }
409         }
410         // Need to check last unaligned bitset for any non zero bit
411         if (ei > 0 && se <= ee) {
412             // Generate the mask of interested bit range
413             Element mask = (1 << ei) - 1;
414             if (mData[se].to_ulong() & mask) {
415                 return true;
416             }
417         }
418         return false;
419     }
420     /* Load bit array values from buffer */
loadFromBuffer(const Buffer & buffer)421     void loadFromBuffer(const Buffer& buffer) {
422         for (size_t i = 0; i < COUNT; i++) {
423             mData[i] = std::bitset<WIDTH>(buffer[i]);
424         }
425     }
426 
427 private:
428     std::array<std::bitset<WIDTH>, COUNT> mData;
429 };
430 
431 class EventHub : public EventHubInterface {
432 public:
433     EventHub();
434 
435     Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const override final;
436 
437     InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const override final;
438 
439     int32_t getDeviceControllerNumber(int32_t deviceId) const override final;
440 
441     void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const override final;
442 
443     status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
444                                  RawAbsoluteAxisInfo* outAxisInfo) const override final;
445 
446     bool hasRelativeAxis(int32_t deviceId, int axis) const override final;
447 
448     bool hasInputProperty(int32_t deviceId, int property) const override final;
449 
450     bool hasMscEvent(int32_t deviceId, int mscEvent) const override final;
451 
452     status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
453                     int32_t* outKeycode, int32_t* outMetaState,
454                     uint32_t* outFlags) const override final;
455 
456     status_t mapAxis(int32_t deviceId, int32_t scanCode,
457                      AxisInfo* outAxisInfo) const override final;
458 
459     base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor(
460             int32_t deviceId, int32_t absCode) override final;
461 
462     const std::vector<int32_t> getRawBatteryIds(int32_t deviceId) override final;
463     std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId,
464                                                     int32_t BatteryId) override final;
465 
466     const std::vector<int32_t> getRawLightIds(int32_t deviceId) override final;
467 
468     std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, int32_t lightId) override final;
469 
470     std::optional<int32_t> getLightBrightness(int32_t deviceId, int32_t lightId) override final;
471     void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) override final;
472     std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities(
473             int32_t deviceId, int32_t lightId) override final;
474     void setLightIntensities(int32_t deviceId, int32_t lightId,
475                              std::unordered_map<LightColor, int32_t> intensities) override final;
476 
477     void setExcludedDevices(const std::vector<std::string>& devices) override final;
478 
479     int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const override final;
480     int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const override final;
481     int32_t getSwitchState(int32_t deviceId, int32_t sw) const override final;
482     status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
483                                   int32_t* outValue) const override final;
484 
485     bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
486                                uint8_t* outFlags) const override final;
487 
488     size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) override final;
489     std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) override final;
490 
491     bool hasScanCode(int32_t deviceId, int32_t scanCode) const override final;
492     bool hasLed(int32_t deviceId, int32_t led) const override final;
493     void setLedState(int32_t deviceId, int32_t led, bool on) override final;
494 
495     void getVirtualKeyDefinitions(
496             int32_t deviceId,
497             std::vector<VirtualKeyDefinition>& outVirtualKeys) const override final;
498 
499     const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap(
500             int32_t deviceId) const override final;
501     bool setKeyboardLayoutOverlay(int32_t deviceId,
502                                   std::shared_ptr<KeyCharacterMap> map) override final;
503 
504     void vibrate(int32_t deviceId, const VibrationElement& effect) override final;
505     void cancelVibrate(int32_t deviceId) override final;
506     std::vector<int32_t> getVibratorIds(int32_t deviceId) override final;
507 
508     void requestReopenDevices() override final;
509 
510     void wake() override final;
511 
512     void dump(std::string& dump) override final;
513 
514     void monitor() override final;
515 
516     std::optional<int32_t> getBatteryCapacity(int32_t deviceId,
517                                               int32_t batteryId) const override final;
518 
519     std::optional<int32_t> getBatteryStatus(int32_t deviceId,
520                                             int32_t batteryId) const override final;
521 
522     bool isDeviceEnabled(int32_t deviceId) override final;
523 
524     status_t enableDevice(int32_t deviceId) override final;
525 
526     status_t disableDevice(int32_t deviceId) override final;
527 
528     ~EventHub() override;
529 
530 private:
531     struct AssociatedDevice {
532         // The device descriptor from evdev device the misc device associated with.
533         std::string descriptor;
534         // The sysfs root path of the misc device.
535         std::filesystem::path sysfsRootPath;
536 
537         int32_t nextBatteryId;
538         int32_t nextLightId;
539         std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
540         std::unordered_map<int32_t, RawLightInfo> lightInfos;
AssociatedDeviceAssociatedDevice541         explicit AssociatedDevice(std::filesystem::path sysfsRootPath)
542               : sysfsRootPath(sysfsRootPath), nextBatteryId(0), nextLightId(0) {}
543         bool configureBatteryLocked();
544         bool configureLightsLocked();
545     };
546 
547     struct Device {
548         int fd; // may be -1 if device is closed
549         const int32_t id;
550         const std::string path;
551         const InputDeviceIdentifier identifier;
552 
553         std::unique_ptr<TouchVideoDevice> videoDevice;
554 
555         Flags<InputDeviceClass> classes;
556 
557         BitArray<KEY_MAX> keyBitmask;
558         BitArray<KEY_MAX> keyState;
559         BitArray<ABS_MAX> absBitmask;
560         BitArray<REL_MAX> relBitmask;
561         BitArray<SW_MAX> swBitmask;
562         BitArray<SW_MAX> swState;
563         BitArray<LED_MAX> ledBitmask;
564         BitArray<FF_MAX> ffBitmask;
565         BitArray<INPUT_PROP_MAX> propBitmask;
566         BitArray<MSC_MAX> mscBitmask;
567 
568         std::string configurationFile;
569         std::unique_ptr<PropertyMap> configuration;
570         std::unique_ptr<VirtualKeyMap> virtualKeyMap;
571         KeyMap keyMap;
572 
573         bool ffEffectPlaying;
574         int16_t ffEffectId; // initially -1
575 
576         // A shared_ptr of a device associated with the input device.
577         // The input devices with same descriptor has the same associated device.
578         std::shared_ptr<AssociatedDevice> associatedDevice;
579 
580         int32_t controllerNumber;
581 
582         Device(int fd, int32_t id, const std::string& path,
583                const InputDeviceIdentifier& identifier);
584         ~Device();
585 
586         void close();
587 
588         bool enabled; // initially true
589         status_t enable();
590         status_t disable();
591         bool hasValidFd() const;
592         const bool isVirtual; // set if fd < 0 is passed to constructor
593 
594         const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap() const;
595 
596         template <std::size_t N>
597         status_t readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray);
598 
599         void configureFd();
600         bool hasKeycodeLocked(int keycode) const;
601         void loadConfigurationLocked();
602         bool loadVirtualKeyMapLocked();
603         status_t loadKeyMapLocked();
604         bool isExternalDeviceLocked();
605         bool deviceHasMicLocked();
606         void setLedForControllerLocked();
607         status_t mapLed(int32_t led, int32_t* outScanCode) const;
608         void setLedStateLocked(int32_t led, bool on);
609     };
610 
611     /**
612      * Create a new device for the provided path.
613      */
614     void openDeviceLocked(const std::string& devicePath) REQUIRES(mLock);
615     void openVideoDeviceLocked(const std::string& devicePath) REQUIRES(mLock);
616     /**
617      * Try to associate a video device with an input device. If the association succeeds,
618      * the videoDevice is moved into the input device. 'videoDevice' will become null if this
619      * happens.
620      * Return true if the association succeeds.
621      * Return false otherwise.
622      */
623     bool tryAddVideoDeviceLocked(Device& device, std::unique_ptr<TouchVideoDevice>& videoDevice)
624             REQUIRES(mLock);
625     void createVirtualKeyboardLocked() REQUIRES(mLock);
626     void addDeviceLocked(std::unique_ptr<Device> device) REQUIRES(mLock);
627     void assignDescriptorLocked(InputDeviceIdentifier& identifier) REQUIRES(mLock);
628 
629     void closeDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock);
630     void closeVideoDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock);
631     void closeDeviceLocked(Device& device) REQUIRES(mLock);
632     void closeAllDevicesLocked() REQUIRES(mLock);
633 
634     status_t registerFdForEpoll(int fd);
635     status_t unregisterFdFromEpoll(int fd);
636     status_t registerDeviceForEpollLocked(Device& device) REQUIRES(mLock);
637     void registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock);
638     status_t unregisterDeviceFromEpollLocked(Device& device) REQUIRES(mLock);
639     void unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock);
640 
641     status_t scanDirLocked(const std::string& dirname) REQUIRES(mLock);
642     status_t scanVideoDirLocked(const std::string& dirname) REQUIRES(mLock);
643     void scanDevicesLocked() REQUIRES(mLock);
644     status_t readNotifyLocked() REQUIRES(mLock);
645 
646     Device* getDeviceByDescriptorLocked(const std::string& descriptor) const REQUIRES(mLock);
647     Device* getDeviceLocked(int32_t deviceId) const REQUIRES(mLock);
648     Device* getDeviceByPathLocked(const std::string& devicePath) const REQUIRES(mLock);
649     /**
650      * Look through all available fd's (both for input devices and for video devices),
651      * and return the device pointer.
652      */
653     Device* getDeviceByFdLocked(int fd) const REQUIRES(mLock);
654 
655     int32_t getNextControllerNumberLocked(const std::string& name) REQUIRES(mLock);
656     void releaseControllerNumberLocked(int32_t num) REQUIRES(mLock);
657     void reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
658                                               Flags<InputDeviceClass> classes) REQUIRES(mLock);
659 
660     const std::unordered_map<int32_t, RawBatteryInfo>& getBatteryInfoLocked(int32_t deviceId) const
661             REQUIRES(mLock);
662 
663     const std::unordered_map<int32_t, RawLightInfo>& getLightInfoLocked(int32_t deviceId) const
664             REQUIRES(mLock);
665 
666     // Protect all internal state.
667     mutable std::mutex mLock;
668 
669     // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none.
670     // EventHub remaps the built-in keyboard to id 0 externally as required by the API.
671     enum {
672         // Must not conflict with any other assigned device ids, including
673         // the virtual keyboard id (-1).
674         NO_BUILT_IN_KEYBOARD = -2,
675     };
676     int32_t mBuiltInKeyboardId;
677 
678     int32_t mNextDeviceId;
679 
680     BitSet32 mControllerNumbers;
681 
682     std::unordered_map<int32_t, std::unique_ptr<Device>> mDevices;
683     /**
684      * Video devices that report touchscreen heatmap, but have not (yet) been paired
685      * with a specific input device. Video device discovery is independent from input device
686      * discovery, so the two types of devices could be found in any order.
687      * Ideally, video devices in this queue do not have an open fd, or at least aren't
688      * actively streaming.
689      */
690     std::vector<std::unique_ptr<TouchVideoDevice>> mUnattachedVideoDevices;
691 
692     std::vector<std::unique_ptr<Device>> mOpeningDevices;
693     std::vector<std::unique_ptr<Device>> mClosingDevices;
694 
695     bool mNeedToSendFinishedDeviceScan;
696     bool mNeedToReopenDevices;
697     bool mNeedToScanDevices;
698     std::vector<std::string> mExcludedDevices;
699 
700     int mEpollFd;
701     int mINotifyFd;
702     int mWakeReadPipeFd;
703     int mWakeWritePipeFd;
704 
705     int mInputWd;
706     int mVideoWd;
707 
708     // Maximum number of signalled FDs to handle at a time.
709     static const int EPOLL_MAX_EVENTS = 16;
710 
711     // The array of pending epoll events and the index of the next event to be handled.
712     struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS];
713     size_t mPendingEventCount;
714     size_t mPendingEventIndex;
715     bool mPendingINotify;
716 };
717 
718 }; // namespace android
719 
720 #endif // _RUNTIME_EVENT_HUB_H
721