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