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