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 //
18 #ifndef _RUNTIME_EVENT_HUB_H
19 #define _RUNTIME_EVENT_HUB_H
20 
21 #include <input/Input.h>
22 #include <input/InputDevice.h>
23 #include <input/Keyboard.h>
24 #include <input/KeyLayoutMap.h>
25 #include <input/KeyCharacterMap.h>
26 #include <input/VirtualKeyMap.h>
27 #include <utils/String8.h>
28 #include <utils/threads.h>
29 #include <utils/Log.h>
30 #include <utils/threads.h>
31 #include <utils/List.h>
32 #include <utils/Errors.h>
33 #include <utils/PropertyMap.h>
34 #include <utils/Vector.h>
35 #include <utils/KeyedVector.h>
36 #include <utils/BitSet.h>
37 
38 #include <linux/input.h>
39 #include <sys/epoll.h>
40 
41 /* Convenience constants. */
42 
43 #define BTN_FIRST 0x100  // first button code
44 #define BTN_LAST 0x15f   // last button code
45 
46 /*
47  * These constants are used privately in Android to pass raw timestamps
48  * through evdev from uinput device drivers because there is currently no
49  * other way to transfer this information.  The evdev driver automatically
50  * timestamps all input events with the time they were posted and clobbers
51  * whatever information was passed in.
52  *
53  * For the purposes of this hack, the timestamp is specified in the
54  * CLOCK_MONOTONIC timebase and is split into two EV_MSC events specifying
55  * seconds and microseconds.
56  */
57 #define MSC_ANDROID_TIME_SEC 0x6
58 #define MSC_ANDROID_TIME_USEC 0x7
59 
60 namespace android {
61 
62 enum {
63     // Device id of a special "virtual" keyboard that is always present.
64     VIRTUAL_KEYBOARD_ID = -1,
65     // Device id of the "built-in" keyboard if there is one.
66     BUILT_IN_KEYBOARD_ID = 0,
67 };
68 
69 /*
70  * A raw event as retrieved from the EventHub.
71  */
72 struct RawEvent {
73     nsecs_t when;
74     int32_t deviceId;
75     int32_t type;
76     int32_t code;
77     int32_t value;
78 };
79 
80 /* Describes an absolute axis. */
81 struct RawAbsoluteAxisInfo {
82     bool valid; // true if the information is valid, false otherwise
83 
84     int32_t minValue;  // minimum value
85     int32_t maxValue;  // maximum value
86     int32_t flat;      // center flat position, eg. flat == 8 means center is between -8 and 8
87     int32_t fuzz;      // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise
88     int32_t resolution; // resolution in units per mm or radians per mm
89 
clearRawAbsoluteAxisInfo90     inline void clear() {
91         valid = false;
92         minValue = 0;
93         maxValue = 0;
94         flat = 0;
95         fuzz = 0;
96         resolution = 0;
97     }
98 };
99 
100 /*
101  * Input device classes.
102  */
103 enum {
104     /* The input device is a keyboard or has buttons. */
105     INPUT_DEVICE_CLASS_KEYBOARD      = 0x00000001,
106 
107     /* The input device is an alpha-numeric keyboard (not just a dial pad). */
108     INPUT_DEVICE_CLASS_ALPHAKEY      = 0x00000002,
109 
110     /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */
111     INPUT_DEVICE_CLASS_TOUCH         = 0x00000004,
112 
113     /* The input device is a cursor device such as a trackball or mouse. */
114     INPUT_DEVICE_CLASS_CURSOR        = 0x00000008,
115 
116     /* The input device is a multi-touch touchscreen. */
117     INPUT_DEVICE_CLASS_TOUCH_MT      = 0x00000010,
118 
119     /* The input device is a directional pad (implies keyboard, has DPAD keys). */
120     INPUT_DEVICE_CLASS_DPAD          = 0x00000020,
121 
122     /* The input device is a gamepad (implies keyboard, has BUTTON keys). */
123     INPUT_DEVICE_CLASS_GAMEPAD       = 0x00000040,
124 
125     /* The input device has switches. */
126     INPUT_DEVICE_CLASS_SWITCH        = 0x00000080,
127 
128     /* The input device is a joystick (implies gamepad, has joystick absolute axes). */
129     INPUT_DEVICE_CLASS_JOYSTICK      = 0x00000100,
130 
131     /* The input device has a vibrator (supports FF_RUMBLE). */
132     INPUT_DEVICE_CLASS_VIBRATOR      = 0x00000200,
133 
134     /* The input device has a microphone. */
135     INPUT_DEVICE_CLASS_MIC           = 0x00000400,
136 
137     /* The input device is an external stylus (has data we want to fuse with touch data). */
138     INPUT_DEVICE_CLASS_EXTERNAL_STYLUS = 0x00000800,
139 
140     /* The input device is virtual (not a real device, not part of UI configuration). */
141     INPUT_DEVICE_CLASS_VIRTUAL       = 0x40000000,
142 
143     /* The input device is external (not built-in). */
144     INPUT_DEVICE_CLASS_EXTERNAL      = 0x80000000,
145 };
146 
147 /*
148  * Gets the class that owns an axis, in cases where multiple classes might claim
149  * the same axis for different purposes.
150  */
151 extern uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses);
152 
153 /*
154  * Grand Central Station for events.
155  *
156  * The event hub aggregates input events received across all known input
157  * devices on the system, including devices that may be emulated by the simulator
158  * environment.  In addition, the event hub generates fake input events to indicate
159  * when devices are added or removed.
160  *
161  * The event hub provides a stream of input events (via the getEvent function).
162  * It also supports querying the current actual state of input devices such as identifying
163  * which keys are currently down.  Finally, the event hub keeps track of the capabilities of
164  * individual input devices, such as their class and the set of key codes that they support.
165  */
166 class EventHubInterface : public virtual RefBase {
167 protected:
EventHubInterface()168     EventHubInterface() { }
~EventHubInterface()169     virtual ~EventHubInterface() { }
170 
171 public:
172     // Synthetic raw event type codes produced when devices are added or removed.
173     enum {
174         // Sent when a device is added.
175         DEVICE_ADDED = 0x10000000,
176         // Sent when a device is removed.
177         DEVICE_REMOVED = 0x20000000,
178         // Sent when all added/removed devices from the most recent scan have been reported.
179         // This event is always sent at least once.
180         FINISHED_DEVICE_SCAN = 0x30000000,
181 
182         FIRST_SYNTHETIC_EVENT = DEVICE_ADDED,
183     };
184 
185     virtual uint32_t getDeviceClasses(int32_t deviceId) const = 0;
186 
187     virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0;
188 
189     virtual int32_t getDeviceControllerNumber(int32_t deviceId) const = 0;
190 
191     virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0;
192 
193     virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
194             RawAbsoluteAxisInfo* outAxisInfo) const = 0;
195 
196     virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0;
197 
198     virtual bool hasInputProperty(int32_t deviceId, int property) const = 0;
199 
200     virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
201             int32_t* outKeycode, uint32_t* outFlags) const = 0;
202 
203     virtual status_t mapAxis(int32_t deviceId, int32_t scanCode,
204             AxisInfo* outAxisInfo) const = 0;
205 
206     // Sets devices that are excluded from opening.
207     // This can be used to ignore input devices for sensors.
208     virtual void setExcludedDevices(const Vector<String8>& devices) = 0;
209 
210     /*
211      * Wait for events to become available and returns them.
212      * After returning, the EventHub holds onto a wake lock until the next call to getEvent.
213      * This ensures that the device will not go to sleep while the event is being processed.
214      * If the device needs to remain awake longer than that, then the caller is responsible
215      * for taking care of it (say, by poking the power manager user activity timer).
216      *
217      * The timeout is advisory only.  If the device is asleep, it will not wake just to
218      * service the timeout.
219      *
220      * Returns the number of events obtained, or 0 if the timeout expired.
221      */
222     virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0;
223 
224     /*
225      * Query current input state.
226      */
227     virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0;
228     virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0;
229     virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0;
230     virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
231             int32_t* outValue) const = 0;
232 
233     /*
234      * Examine key input devices for specific framework keycode support
235      */
236     virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
237             uint8_t* outFlags) const = 0;
238 
239     virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0;
240 
241     /* LED related functions expect Android LED constants, not scan codes or HID usages */
242     virtual bool hasLed(int32_t deviceId, int32_t led) const = 0;
243     virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0;
244 
245     virtual void getVirtualKeyDefinitions(int32_t deviceId,
246             Vector<VirtualKeyDefinition>& outVirtualKeys) const = 0;
247 
248     virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0;
249     virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map) = 0;
250 
251     /* Control the vibrator. */
252     virtual void vibrate(int32_t deviceId, nsecs_t duration) = 0;
253     virtual void cancelVibrate(int32_t deviceId) = 0;
254 
255     /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */
256     virtual void requestReopenDevices() = 0;
257 
258     /* Wakes up getEvents() if it is blocked on a read. */
259     virtual void wake() = 0;
260 
261     /* Dump EventHub state to a string. */
262     virtual void dump(String8& dump) = 0;
263 
264     /* Called by the heatbeat to ensures that the reader has not deadlocked. */
265     virtual void monitor() = 0;
266 };
267 
268 class EventHub : public EventHubInterface
269 {
270 public:
271     EventHub();
272 
273     virtual uint32_t getDeviceClasses(int32_t deviceId) const;
274 
275     virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const;
276 
277     virtual int32_t getDeviceControllerNumber(int32_t deviceId) const;
278 
279     virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const;
280 
281     virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
282             RawAbsoluteAxisInfo* outAxisInfo) const;
283 
284     virtual bool hasRelativeAxis(int32_t deviceId, int axis) const;
285 
286     virtual bool hasInputProperty(int32_t deviceId, int property) const;
287 
288     virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
289             int32_t* outKeycode, uint32_t* outFlags) const;
290 
291     virtual status_t mapAxis(int32_t deviceId, int32_t scanCode,
292             AxisInfo* outAxisInfo) const;
293 
294     virtual void setExcludedDevices(const Vector<String8>& devices);
295 
296     virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const;
297     virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const;
298     virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const;
299     virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const;
300 
301     virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
302             const int32_t* keyCodes, uint8_t* outFlags) const;
303 
304     virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize);
305 
306     virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const;
307     virtual bool hasLed(int32_t deviceId, int32_t led) const;
308     virtual void setLedState(int32_t deviceId, int32_t led, bool on);
309 
310     virtual void getVirtualKeyDefinitions(int32_t deviceId,
311             Vector<VirtualKeyDefinition>& outVirtualKeys) const;
312 
313     virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const;
314     virtual bool setKeyboardLayoutOverlay(int32_t deviceId, const sp<KeyCharacterMap>& map);
315 
316     virtual void vibrate(int32_t deviceId, nsecs_t duration);
317     virtual void cancelVibrate(int32_t deviceId);
318 
319     virtual void requestReopenDevices();
320 
321     virtual void wake();
322 
323     virtual void dump(String8& dump);
324     virtual void monitor();
325 
326 protected:
327     virtual ~EventHub();
328 
329 private:
330     struct Device {
331         Device* next;
332 
333         int fd; // may be -1 if device is virtual
334         const int32_t id;
335         const String8 path;
336         const InputDeviceIdentifier identifier;
337 
338         uint32_t classes;
339 
340         uint8_t keyBitmask[(KEY_MAX + 1) / 8];
341         uint8_t absBitmask[(ABS_MAX + 1) / 8];
342         uint8_t relBitmask[(REL_MAX + 1) / 8];
343         uint8_t swBitmask[(SW_MAX + 1) / 8];
344         uint8_t ledBitmask[(LED_MAX + 1) / 8];
345         uint8_t ffBitmask[(FF_MAX + 1) / 8];
346         uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8];
347 
348         String8 configurationFile;
349         PropertyMap* configuration;
350         VirtualKeyMap* virtualKeyMap;
351         KeyMap keyMap;
352 
353         sp<KeyCharacterMap> overlayKeyMap;
354         sp<KeyCharacterMap> combinedKeyMap;
355 
356         bool ffEffectPlaying;
357         int16_t ffEffectId; // initially -1
358 
359         int32_t controllerNumber;
360 
361         int32_t timestampOverrideSec;
362         int32_t timestampOverrideUsec;
363 
364         Device(int fd, int32_t id, const String8& path, const InputDeviceIdentifier& identifier);
365         ~Device();
366 
367         void close();
368 
isVirtualDevice369         inline bool isVirtual() const { return fd < 0; }
370 
getKeyCharacterMapDevice371         const sp<KeyCharacterMap>& getKeyCharacterMap() const {
372             if (combinedKeyMap != NULL) {
373                 return combinedKeyMap;
374             }
375             return keyMap.keyCharacterMap;
376         }
377     };
378 
379     status_t openDeviceLocked(const char *devicePath);
380     void createVirtualKeyboardLocked();
381     void addDeviceLocked(Device* device);
382     void assignDescriptorLocked(InputDeviceIdentifier& identifier);
383 
384     status_t closeDeviceByPathLocked(const char *devicePath);
385     void closeDeviceLocked(Device* device);
386     void closeAllDevicesLocked();
387 
388     status_t scanDirLocked(const char *dirname);
389     void scanDevicesLocked();
390     status_t readNotifyLocked();
391 
392     Device* getDeviceByDescriptorLocked(String8& descriptor) const;
393     Device* getDeviceLocked(int32_t deviceId) const;
394     Device* getDeviceByPathLocked(const char* devicePath) const;
395 
396     bool hasKeycodeLocked(Device* device, int keycode) const;
397 
398     void loadConfigurationLocked(Device* device);
399     status_t loadVirtualKeyMapLocked(Device* device);
400     status_t loadKeyMapLocked(Device* device);
401 
402     bool isExternalDeviceLocked(Device* device);
403     bool deviceHasMicLocked(Device* device);
404 
405     int32_t getNextControllerNumberLocked(Device* device);
406     void releaseControllerNumberLocked(Device* device);
407     void setLedForController(Device* device);
408 
409     status_t mapLed(Device* device, int32_t led, int32_t* outScanCode) const;
410     void setLedStateLocked(Device* device, int32_t led, bool on);
411 
412     // Protect all internal state.
413     mutable Mutex mLock;
414 
415     // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none.
416     // EventHub remaps the built-in keyboard to id 0 externally as required by the API.
417     enum {
418         // Must not conflict with any other assigned device ids, including
419         // the virtual keyboard id (-1).
420         NO_BUILT_IN_KEYBOARD = -2,
421     };
422     int32_t mBuiltInKeyboardId;
423 
424     int32_t mNextDeviceId;
425 
426     BitSet32 mControllerNumbers;
427 
428     KeyedVector<int32_t, Device*> mDevices;
429 
430     Device *mOpeningDevices;
431     Device *mClosingDevices;
432 
433     bool mNeedToSendFinishedDeviceScan;
434     bool mNeedToReopenDevices;
435     bool mNeedToScanDevices;
436     Vector<String8> mExcludedDevices;
437 
438     int mEpollFd;
439     int mINotifyFd;
440     int mWakeReadPipeFd;
441     int mWakeWritePipeFd;
442 
443     // Ids used for epoll notifications not associated with devices.
444     static const uint32_t EPOLL_ID_INOTIFY = 0x80000001;
445     static const uint32_t EPOLL_ID_WAKE = 0x80000002;
446 
447     // Epoll FD list size hint.
448     static const int EPOLL_SIZE_HINT = 8;
449 
450     // Maximum number of signalled FDs to handle at a time.
451     static const int EPOLL_MAX_EVENTS = 16;
452 
453     // The array of pending epoll events and the index of the next event to be handled.
454     struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS];
455     size_t mPendingEventCount;
456     size_t mPendingEventIndex;
457     bool mPendingINotify;
458 
459     bool mUsingEpollWakeup;
460 };
461 
462 }; // namespace android
463 
464 #endif // _RUNTIME_EVENT_HUB_H
465