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