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