EventHub.h revision 9f25b7fdf216c9ef0bd2322cd223eeaf0d60f77f
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 <androidfw/Input.h>
22#include <androidfw/InputDevice.h>
23#include <androidfw/Keyboard.h>
24#include <androidfw/KeyLayoutMap.h>
25#include <androidfw/KeyCharacterMap.h>
26#include <androidfw/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
37#include <linux/input.h>
38#include <sys/epoll.h>
39
40/* Convenience constants. */
41
42#define BTN_FIRST 0x100  // first button scancode
43#define BTN_LAST 0x15f   // last button scancode
44
45namespace android {
46
47enum {
48    // Device id of a special "virtual" keyboard that is always present.
49    VIRTUAL_KEYBOARD_ID = -1,
50    // Device id of the "built-in" keyboard if there is one.
51    BUILT_IN_KEYBOARD_ID = 0,
52};
53
54/*
55 * A raw event as retrieved from the EventHub.
56 */
57struct RawEvent {
58    nsecs_t when;
59    int32_t deviceId;
60    int32_t type;
61    int32_t scanCode;
62    int32_t keyCode;
63    int32_t value;
64    uint32_t flags;
65};
66
67/* Describes an absolute axis. */
68struct 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
77    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 */
90enum {
91    /* The input device is a keyboard or has buttons. */
92    INPUT_DEVICE_CLASS_KEYBOARD      = 0x00000001,
93
94    /* The input device is an alpha-numeric keyboard (not just a dial pad). */
95    INPUT_DEVICE_CLASS_ALPHAKEY      = 0x00000002,
96
97    /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */
98    INPUT_DEVICE_CLASS_TOUCH         = 0x00000004,
99
100    /* The input device is a cursor device such as a trackball or mouse. */
101    INPUT_DEVICE_CLASS_CURSOR        = 0x00000008,
102
103    /* The input device is a multi-touch touchscreen. */
104    INPUT_DEVICE_CLASS_TOUCH_MT      = 0x00000010,
105
106    /* The input device is a directional pad (implies keyboard, has DPAD keys). */
107    INPUT_DEVICE_CLASS_DPAD          = 0x00000020,
108
109    /* The input device is a gamepad (implies keyboard, has BUTTON keys). */
110    INPUT_DEVICE_CLASS_GAMEPAD       = 0x00000040,
111
112    /* The input device has switches. */
113    INPUT_DEVICE_CLASS_SWITCH        = 0x00000080,
114
115    /* The input device is a joystick (implies gamepad, has joystick absolute axes). */
116    INPUT_DEVICE_CLASS_JOYSTICK      = 0x00000100,
117
118    /* The input device is virtual (not a real device, not part of UI configuration). */
119    INPUT_DEVICE_CLASS_VIRTUAL       = 0x40000000,
120
121    /* The input device is external (not built-in). */
122    INPUT_DEVICE_CLASS_EXTERNAL      = 0x80000000,
123};
124
125/*
126 * Gets the class that owns an axis, in cases where multiple classes might claim
127 * the same axis for different purposes.
128 */
129extern uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses);
130
131/*
132 * Grand Central Station for events.
133 *
134 * The event hub aggregates input events received across all known input
135 * devices on the system, including devices that may be emulated by the simulator
136 * environment.  In addition, the event hub generates fake input events to indicate
137 * when devices are added or removed.
138 *
139 * The event hub provides a stream of input events (via the getEvent function).
140 * It also supports querying the current actual state of input devices such as identifying
141 * which keys are currently down.  Finally, the event hub keeps track of the capabilities of
142 * individual input devices, such as their class and the set of key codes that they support.
143 */
144class EventHubInterface : public virtual RefBase {
145protected:
146    EventHubInterface() { }
147    virtual ~EventHubInterface() { }
148
149public:
150    // Synthetic raw event type codes produced when devices are added or removed.
151    enum {
152        // Sent when a device is added.
153        DEVICE_ADDED = 0x10000000,
154        // Sent when a device is removed.
155        DEVICE_REMOVED = 0x20000000,
156        // Sent when all added/removed devices from the most recent scan have been reported.
157        // This event is always sent at least once.
158        FINISHED_DEVICE_SCAN = 0x30000000,
159
160        FIRST_SYNTHETIC_EVENT = DEVICE_ADDED,
161    };
162
163    virtual uint32_t getDeviceClasses(int32_t deviceId) const = 0;
164
165    virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0;
166
167    virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const = 0;
168
169    virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
170            RawAbsoluteAxisInfo* outAxisInfo) const = 0;
171
172    virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0;
173
174    virtual bool hasInputProperty(int32_t deviceId, int property) const = 0;
175
176    virtual status_t mapKey(int32_t deviceId, int scancode,
177            int32_t* outKeycode, uint32_t* outFlags) const = 0;
178
179    virtual status_t mapAxis(int32_t deviceId, int scancode,
180            AxisInfo* outAxisInfo) const = 0;
181
182    // Sets devices that are excluded from opening.
183    // This can be used to ignore input devices for sensors.
184    virtual void setExcludedDevices(const Vector<String8>& devices) = 0;
185
186    /*
187     * Wait for events to become available and returns them.
188     * After returning, the EventHub holds onto a wake lock until the next call to getEvent.
189     * This ensures that the device will not go to sleep while the event is being processed.
190     * If the device needs to remain awake longer than that, then the caller is responsible
191     * for taking care of it (say, by poking the power manager user activity timer).
192     *
193     * The timeout is advisory only.  If the device is asleep, it will not wake just to
194     * service the timeout.
195     *
196     * Returns the number of events obtained, or 0 if the timeout expired.
197     */
198    virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) = 0;
199
200    /*
201     * Query current input state.
202     */
203    virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0;
204    virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0;
205    virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0;
206    virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
207            int32_t* outValue) const = 0;
208
209    /*
210     * Examine key input devices for specific framework keycode support
211     */
212    virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
213            uint8_t* outFlags) const = 0;
214
215    virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0;
216    virtual bool hasLed(int32_t deviceId, int32_t led) const = 0;
217    virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0;
218
219    virtual void getVirtualKeyDefinitions(int32_t deviceId,
220            Vector<VirtualKeyDefinition>& outVirtualKeys) const = 0;
221
222    virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0;
223
224    /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */
225    virtual void requestReopenDevices() = 0;
226
227    /* Wakes up getEvents() if it is blocked on a read. */
228    virtual void wake() = 0;
229
230    /* Dump EventHub state to a string. */
231    virtual void dump(String8& dump) = 0;
232
233    /* Called by the heatbeat to ensures that the reader has not deadlocked. */
234    virtual void monitor() = 0;
235};
236
237class EventHub : public EventHubInterface
238{
239public:
240    EventHub();
241
242    virtual uint32_t getDeviceClasses(int32_t deviceId) const;
243
244    virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const;
245
246    virtual void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const;
247
248    virtual status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
249            RawAbsoluteAxisInfo* outAxisInfo) const;
250
251    virtual bool hasRelativeAxis(int32_t deviceId, int axis) const;
252
253    virtual bool hasInputProperty(int32_t deviceId, int property) const;
254
255    virtual status_t mapKey(int32_t deviceId, int scancode,
256            int32_t* outKeycode, uint32_t* outFlags) const;
257
258    virtual status_t mapAxis(int32_t deviceId, int scancode,
259            AxisInfo* outAxisInfo) const;
260
261    virtual void setExcludedDevices(const Vector<String8>& devices);
262
263    virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const;
264    virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const;
265    virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const;
266    virtual status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const;
267
268    virtual bool markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
269            const int32_t* keyCodes, uint8_t* outFlags) const;
270
271    virtual size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize);
272
273    virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const;
274    virtual bool hasLed(int32_t deviceId, int32_t led) const;
275    virtual void setLedState(int32_t deviceId, int32_t led, bool on);
276
277    virtual void getVirtualKeyDefinitions(int32_t deviceId,
278            Vector<VirtualKeyDefinition>& outVirtualKeys) const;
279
280    virtual sp<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const;
281
282    virtual void requestReopenDevices();
283
284    virtual void wake();
285
286    virtual void dump(String8& dump);
287    virtual void monitor();
288
289protected:
290    virtual ~EventHub();
291
292private:
293    struct Device {
294        Device* next;
295
296        int fd; // may be -1 if device is virtual
297        const int32_t id;
298        const String8 path;
299        const InputDeviceIdentifier identifier;
300
301        uint32_t classes;
302
303        uint8_t keyBitmask[(KEY_MAX + 1) / 8];
304        uint8_t absBitmask[(ABS_MAX + 1) / 8];
305        uint8_t relBitmask[(REL_MAX + 1) / 8];
306        uint8_t swBitmask[(SW_MAX + 1) / 8];
307        uint8_t ledBitmask[(LED_MAX + 1) / 8];
308        uint8_t propBitmask[(INPUT_PROP_MAX + 1) / 8];
309
310        String8 configurationFile;
311        PropertyMap* configuration;
312        VirtualKeyMap* virtualKeyMap;
313        KeyMap keyMap;
314
315        Device(int fd, int32_t id, const String8& path, const InputDeviceIdentifier& identifier);
316        ~Device();
317
318        void close();
319
320        inline bool isVirtual() const { return fd < 0; }
321    };
322
323    status_t openDeviceLocked(const char *devicePath);
324    void createVirtualKeyboardLocked();
325    void addDeviceLocked(Device* device);
326
327    status_t closeDeviceByPathLocked(const char *devicePath);
328    void closeDeviceLocked(Device* device);
329    void closeAllDevicesLocked();
330
331    status_t scanDirLocked(const char *dirname);
332    void scanDevicesLocked();
333    status_t readNotifyLocked();
334
335    Device* getDeviceLocked(int32_t deviceId) const;
336    Device* getDeviceByPathLocked(const char* devicePath) const;
337
338    bool hasKeycodeLocked(Device* device, int keycode) const;
339
340    void loadConfigurationLocked(Device* device);
341    status_t loadVirtualKeyMapLocked(Device* device);
342    status_t loadKeyMapLocked(Device* device);
343
344    bool isExternalDeviceLocked(Device* device);
345
346    // Protect all internal state.
347    mutable Mutex mLock;
348
349    // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none.
350    // EventHub remaps the built-in keyboard to id 0 externally as required by the API.
351    enum {
352        // Must not conflict with any other assigned device ids, including
353        // the virtual keyboard id (-1).
354        NO_BUILT_IN_KEYBOARD = -2,
355    };
356    int32_t mBuiltInKeyboardId;
357
358    int32_t mNextDeviceId;
359
360    KeyedVector<int32_t, Device*> mDevices;
361
362    Device *mOpeningDevices;
363    Device *mClosingDevices;
364
365    bool mNeedToSendFinishedDeviceScan;
366    bool mNeedToReopenDevices;
367    bool mNeedToScanDevices;
368    Vector<String8> mExcludedDevices;
369
370    int mEpollFd;
371    int mINotifyFd;
372    int mWakeReadPipeFd;
373    int mWakeWritePipeFd;
374
375    // Ids used for epoll notifications not associated with devices.
376    static const uint32_t EPOLL_ID_INOTIFY = 0x80000001;
377    static const uint32_t EPOLL_ID_WAKE = 0x80000002;
378
379    // Epoll FD list size hint.
380    static const int EPOLL_SIZE_HINT = 8;
381
382    // Maximum number of signalled FDs to handle at a time.
383    static const int EPOLL_MAX_EVENTS = 16;
384
385    // The array of pending epoll events and the index of the next event to be handled.
386    struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS];
387    size_t mPendingEventCount;
388    size_t mPendingEventIndex;
389    bool mPendingINotify;
390};
391
392}; // namespace android
393
394#endif // _RUNTIME_EVENT_HUB_H
395