1//
2// Copyright 2005 The Android Open Source Project
3//
4// Handle events, like key input and vsync.
5//
6// The goal is to provide an optimized solution for Linux, not an
7// implementation that works well across all platforms.  We expect
8// events to arrive on file descriptors, so that we can use a select()
9// select() call to sleep.
10//
11// We can't select() on anything but network sockets in Windows, so we
12// provide an alternative implementation of waitEvent for that platform.
13//
14#define LOG_TAG "EventHub"
15
16//#define LOG_NDEBUG 0
17
18#include <ui/EventHub.h>
19#include <ui/KeycodeLabels.h>
20#include <hardware_legacy/power.h>
21
22#include <cutils/properties.h>
23#include <utils/Log.h>
24#include <utils/Timers.h>
25#include <utils/threads.h>
26#include <utils/Errors.h>
27
28#include <stdlib.h>
29#include <stdio.h>
30#include <unistd.h>
31#include <fcntl.h>
32#include <memory.h>
33#include <errno.h>
34#include <assert.h>
35
36#include "KeyLayoutMap.h"
37
38#include <string.h>
39#include <stdint.h>
40#include <dirent.h>
41#ifdef HAVE_INOTIFY
42# include <sys/inotify.h>
43#endif
44#ifdef HAVE_ANDROID_OS
45# include <sys/limits.h>        /* not part of Linux */
46#endif
47#include <sys/poll.h>
48#include <sys/ioctl.h>
49
50/* this macro is used to tell if "bit" is set in "array"
51 * it selects a byte from the array, and does a boolean AND
52 * operation with a byte that only has the relevant bit set.
53 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
54 */
55#define test_bit(bit, array)    (array[bit/8] & (1<<(bit%8)))
56
57/* this macro computes the number of bytes needed to represent a bit array of the specified size */
58#define sizeof_bit_array(bits)  ((bits + 7) / 8)
59
60#define ID_MASK  0x0000ffff
61#define SEQ_MASK 0x7fff0000
62#define SEQ_SHIFT 16
63
64#ifndef ABS_MT_TOUCH_MAJOR
65#define ABS_MT_TOUCH_MAJOR      0x30    /* Major axis of touching ellipse */
66#endif
67
68#ifndef ABS_MT_POSITION_X
69#define ABS_MT_POSITION_X       0x35    /* Center X ellipse position */
70#endif
71
72#ifndef ABS_MT_POSITION_Y
73#define ABS_MT_POSITION_Y       0x36    /* Center Y ellipse position */
74#endif
75
76#define INDENT "  "
77#define INDENT2 "    "
78#define INDENT3 "      "
79
80namespace android {
81
82static const char *WAKE_LOCK_ID = "KeyEvents";
83static const char *device_path = "/dev/input";
84
85/* return the larger integer */
86static inline int max(int v1, int v2)
87{
88    return (v1 > v2) ? v1 : v2;
89}
90
91static inline const char* toString(bool value) {
92    return value ? "true" : "false";
93}
94
95EventHub::device_t::device_t(int32_t _id, const char* _path, const char* name)
96    : id(_id), path(_path), name(name), classes(0)
97    , keyBitmask(NULL), layoutMap(new KeyLayoutMap()), fd(-1), next(NULL) {
98}
99
100EventHub::device_t::~device_t() {
101    delete [] keyBitmask;
102    delete layoutMap;
103}
104
105EventHub::EventHub(void)
106    : mError(NO_INIT), mHaveFirstKeyboard(false), mFirstKeyboardId(0)
107    , mDevicesById(0), mNumDevicesById(0)
108    , mOpeningDevices(0), mClosingDevices(0)
109    , mDevices(0), mFDs(0), mFDCount(0), mOpened(false), mNeedToSendFinishedDeviceScan(false)
110    , mInputBufferIndex(0), mInputBufferCount(0), mInputDeviceIndex(0)
111{
112    acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
113#ifdef EV_SW
114    memset(mSwitches, 0, sizeof(mSwitches));
115#endif
116}
117
118/*
119 * Clean up.
120 */
121EventHub::~EventHub(void)
122{
123    release_wake_lock(WAKE_LOCK_ID);
124    // we should free stuff here...
125}
126
127status_t EventHub::errorCheck() const
128{
129    return mError;
130}
131
132String8 EventHub::getDeviceName(int32_t deviceId) const
133{
134    AutoMutex _l(mLock);
135    device_t* device = getDeviceLocked(deviceId);
136    if (device == NULL) return String8();
137    return device->name;
138}
139
140uint32_t EventHub::getDeviceClasses(int32_t deviceId) const
141{
142    AutoMutex _l(mLock);
143    device_t* device = getDeviceLocked(deviceId);
144    if (device == NULL) return 0;
145    return device->classes;
146}
147
148status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
149        RawAbsoluteAxisInfo* outAxisInfo) const {
150    outAxisInfo->clear();
151
152    AutoMutex _l(mLock);
153    device_t* device = getDeviceLocked(deviceId);
154    if (device == NULL) return -1;
155
156    struct input_absinfo info;
157
158    if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
159        LOGW("Error reading absolute controller %d for device %s fd %d\n",
160             axis, device->name.string(), device->fd);
161        return -errno;
162    }
163
164    if (info.minimum != info.maximum) {
165        outAxisInfo->valid = true;
166        outAxisInfo->minValue = info.minimum;
167        outAxisInfo->maxValue = info.maximum;
168        outAxisInfo->flat = info.flat;
169        outAxisInfo->fuzz = info.fuzz;
170    }
171    return OK;
172}
173
174int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
175    if (scanCode >= 0 && scanCode <= KEY_MAX) {
176        AutoMutex _l(mLock);
177
178        device_t* device = getDeviceLocked(deviceId);
179        if (device != NULL) {
180            return getScanCodeStateLocked(device, scanCode);
181        }
182    }
183    return AKEY_STATE_UNKNOWN;
184}
185
186int32_t EventHub::getScanCodeStateLocked(device_t* device, int32_t scanCode) const {
187    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
188    memset(key_bitmask, 0, sizeof(key_bitmask));
189    if (ioctl(device->fd,
190               EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
191        return test_bit(scanCode, key_bitmask) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
192    }
193    return AKEY_STATE_UNKNOWN;
194}
195
196int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
197    AutoMutex _l(mLock);
198
199    device_t* device = getDeviceLocked(deviceId);
200    if (device != NULL) {
201        return getKeyCodeStateLocked(device, keyCode);
202    }
203    return AKEY_STATE_UNKNOWN;
204}
205
206int32_t EventHub::getKeyCodeStateLocked(device_t* device, int32_t keyCode) const {
207    Vector<int32_t> scanCodes;
208    device->layoutMap->findScancodes(keyCode, &scanCodes);
209
210    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
211    memset(key_bitmask, 0, sizeof(key_bitmask));
212    if (ioctl(device->fd, EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
213        #if 0
214        for (size_t i=0; i<=KEY_MAX; i++) {
215            LOGI("(Scan code %d: down=%d)", i, test_bit(i, key_bitmask));
216        }
217        #endif
218        const size_t N = scanCodes.size();
219        for (size_t i=0; i<N && i<=KEY_MAX; i++) {
220            int32_t sc = scanCodes.itemAt(i);
221            //LOGI("Code %d: down=%d", sc, test_bit(sc, key_bitmask));
222            if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, key_bitmask)) {
223                return AKEY_STATE_DOWN;
224            }
225        }
226        return AKEY_STATE_UP;
227    }
228    return AKEY_STATE_UNKNOWN;
229}
230
231int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
232#ifdef EV_SW
233    if (sw >= 0 && sw <= SW_MAX) {
234        AutoMutex _l(mLock);
235
236        device_t* device = getDeviceLocked(deviceId);
237        if (device != NULL) {
238            return getSwitchStateLocked(device, sw);
239        }
240    }
241#endif
242    return AKEY_STATE_UNKNOWN;
243}
244
245int32_t EventHub::getSwitchStateLocked(device_t* device, int32_t sw) const {
246    uint8_t sw_bitmask[sizeof_bit_array(SW_MAX + 1)];
247    memset(sw_bitmask, 0, sizeof(sw_bitmask));
248    if (ioctl(device->fd,
249               EVIOCGSW(sizeof(sw_bitmask)), sw_bitmask) >= 0) {
250        return test_bit(sw, sw_bitmask) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
251    }
252    return AKEY_STATE_UNKNOWN;
253}
254
255bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
256        const int32_t* keyCodes, uint8_t* outFlags) const {
257    AutoMutex _l(mLock);
258
259    device_t* device = getDeviceLocked(deviceId);
260    if (device != NULL) {
261        return markSupportedKeyCodesLocked(device, numCodes, keyCodes, outFlags);
262    }
263    return false;
264}
265
266bool EventHub::markSupportedKeyCodesLocked(device_t* device, size_t numCodes,
267        const int32_t* keyCodes, uint8_t* outFlags) const {
268    if (device->layoutMap == NULL || device->keyBitmask == NULL) {
269        return false;
270    }
271
272    Vector<int32_t> scanCodes;
273    for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
274        scanCodes.clear();
275
276        status_t err = device->layoutMap->findScancodes(keyCodes[codeIndex], &scanCodes);
277        if (! err) {
278            // check the possible scan codes identified by the layout map against the
279            // map of codes actually emitted by the driver
280            for (size_t sc = 0; sc < scanCodes.size(); sc++) {
281                if (test_bit(scanCodes[sc], device->keyBitmask)) {
282                    outFlags[codeIndex] = 1;
283                    break;
284                }
285            }
286        }
287    }
288    return true;
289}
290
291status_t EventHub::scancodeToKeycode(int32_t deviceId, int scancode,
292        int32_t* outKeycode, uint32_t* outFlags) const
293{
294    AutoMutex _l(mLock);
295    device_t* device = getDeviceLocked(deviceId);
296
297    if (device != NULL && device->layoutMap != NULL) {
298        status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
299        if (err == NO_ERROR) {
300            return NO_ERROR;
301        }
302    }
303
304    if (mHaveFirstKeyboard) {
305        device = getDeviceLocked(mFirstKeyboardId);
306
307        if (device != NULL && device->layoutMap != NULL) {
308            status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
309            if (err == NO_ERROR) {
310                return NO_ERROR;
311            }
312        }
313    }
314
315    *outKeycode = 0;
316    *outFlags = 0;
317    return NAME_NOT_FOUND;
318}
319
320void EventHub::addExcludedDevice(const char* deviceName)
321{
322    AutoMutex _l(mLock);
323
324    String8 name(deviceName);
325    mExcludedDevices.push_back(name);
326}
327
328EventHub::device_t* EventHub::getDeviceLocked(int32_t deviceId) const
329{
330    if (deviceId == 0) deviceId = mFirstKeyboardId;
331    int32_t id = deviceId & ID_MASK;
332    if (id >= mNumDevicesById || id < 0) return NULL;
333    device_t* dev = mDevicesById[id].device;
334    if (dev == NULL) return NULL;
335    if (dev->id == deviceId) {
336        return dev;
337    }
338    return NULL;
339}
340
341bool EventHub::getEvent(RawEvent* outEvent)
342{
343    outEvent->deviceId = 0;
344    outEvent->type = 0;
345    outEvent->scanCode = 0;
346    outEvent->keyCode = 0;
347    outEvent->flags = 0;
348    outEvent->value = 0;
349    outEvent->when = 0;
350
351    // Note that we only allow one caller to getEvent(), so don't need
352    // to do locking here...  only when adding/removing devices.
353
354    if (!mOpened) {
355        mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;
356        mOpened = true;
357        mNeedToSendFinishedDeviceScan = true;
358    }
359
360    for (;;) {
361        // Report any devices that had last been added/removed.
362        if (mClosingDevices != NULL) {
363            device_t* device = mClosingDevices;
364            LOGV("Reporting device closed: id=0x%x, name=%s\n",
365                 device->id, device->path.string());
366            mClosingDevices = device->next;
367            if (device->id == mFirstKeyboardId) {
368                outEvent->deviceId = 0;
369            } else {
370                outEvent->deviceId = device->id;
371            }
372            outEvent->type = DEVICE_REMOVED;
373            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
374            delete device;
375            mNeedToSendFinishedDeviceScan = true;
376            return true;
377        }
378
379        if (mOpeningDevices != NULL) {
380            device_t* device = mOpeningDevices;
381            LOGV("Reporting device opened: id=0x%x, name=%s\n",
382                 device->id, device->path.string());
383            mOpeningDevices = device->next;
384            if (device->id == mFirstKeyboardId) {
385                outEvent->deviceId = 0;
386            } else {
387                outEvent->deviceId = device->id;
388            }
389            outEvent->type = DEVICE_ADDED;
390            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
391            mNeedToSendFinishedDeviceScan = true;
392            return true;
393        }
394
395        if (mNeedToSendFinishedDeviceScan) {
396            mNeedToSendFinishedDeviceScan = false;
397            outEvent->type = FINISHED_DEVICE_SCAN;
398            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
399            return true;
400        }
401
402        // Grab the next input event.
403        for (;;) {
404            // Consume buffered input events, if any.
405            if (mInputBufferIndex < mInputBufferCount) {
406                const struct input_event& iev = mInputBufferData[mInputBufferIndex++];
407                const device_t* device = mDevices[mInputDeviceIndex];
408
409                LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d", device->path.string(),
410                     (int) iev.time.tv_sec, (int) iev.time.tv_usec, iev.type, iev.code, iev.value);
411                if (device->id == mFirstKeyboardId) {
412                    outEvent->deviceId = 0;
413                } else {
414                    outEvent->deviceId = device->id;
415                }
416                outEvent->type = iev.type;
417                outEvent->scanCode = iev.code;
418                if (iev.type == EV_KEY) {
419                    status_t err = device->layoutMap->map(iev.code,
420                            & outEvent->keyCode, & outEvent->flags);
421                    LOGV("iev.code=%d keyCode=%d flags=0x%08x err=%d\n",
422                        iev.code, outEvent->keyCode, outEvent->flags, err);
423                    if (err != 0) {
424                        outEvent->keyCode = AKEYCODE_UNKNOWN;
425                        outEvent->flags = 0;
426                    }
427                } else {
428                    outEvent->keyCode = iev.code;
429                }
430                outEvent->value = iev.value;
431
432                // Use an event timestamp in the same timebase as
433                // java.lang.System.nanoTime() and android.os.SystemClock.uptimeMillis()
434                // as expected by the rest of the system.
435                outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
436                return true;
437            }
438
439            // Finish reading all events from devices identified in previous poll().
440            // This code assumes that mInputDeviceIndex is initially 0 and that the
441            // revents member of pollfd is initialized to 0 when the device is first added.
442            // Since mFDs[0] is used for inotify, we process regular events starting at index 1.
443            mInputDeviceIndex += 1;
444            if (mInputDeviceIndex >= mFDCount) {
445                break;
446            }
447
448            const struct pollfd& pfd = mFDs[mInputDeviceIndex];
449            if (pfd.revents & POLLIN) {
450                int32_t readSize = read(pfd.fd, mInputBufferData,
451                        sizeof(struct input_event) * INPUT_BUFFER_SIZE);
452                if (readSize < 0) {
453                    if (errno != EAGAIN && errno != EINTR) {
454                        LOGW("could not get event (errno=%d)", errno);
455                    }
456                } else if ((readSize % sizeof(struct input_event)) != 0) {
457                    LOGE("could not get event (wrong size: %d)", readSize);
458                } else {
459                    mInputBufferCount = readSize / sizeof(struct input_event);
460                    mInputBufferIndex = 0;
461                }
462            }
463        }
464
465#if HAVE_INOTIFY
466        // readNotify() will modify mFDs and mFDCount, so this must be done after
467        // processing all other events.
468        if(mFDs[0].revents & POLLIN) {
469            readNotify(mFDs[0].fd);
470            mFDs[0].revents = 0;
471            continue; // report added or removed devices immediately
472        }
473#endif
474
475        mInputDeviceIndex = 0;
476
477        // Poll for events.  Mind the wake lock dance!
478        // We hold a wake lock at all times except during poll().  This works due to some
479        // subtle choreography.  When a device driver has pending (unread) events, it acquires
480        // a kernel wake lock.  However, once the last pending event has been read, the device
481        // driver will release the kernel wake lock.  To prevent the system from going to sleep
482        // when this happens, the EventHub holds onto its own user wake lock while the client
483        // is processing events.  Thus the system can only sleep if there are no events
484        // pending or currently being processed.
485        release_wake_lock(WAKE_LOCK_ID);
486
487        int pollResult = poll(mFDs, mFDCount, -1);
488
489        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
490
491        if (pollResult <= 0) {
492            if (errno != EINTR) {
493                LOGW("poll failed (errno=%d)\n", errno);
494                usleep(100000);
495            }
496        }
497    }
498}
499
500/*
501 * Open the platform-specific input device.
502 */
503bool EventHub::openPlatformInput(void)
504{
505    /*
506     * Open platform-specific input device(s).
507     */
508    int res;
509
510    mFDCount = 1;
511    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));
512    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));
513    mFDs[0].events = POLLIN;
514    mFDs[0].revents = 0;
515    mDevices[0] = NULL;
516#ifdef HAVE_INOTIFY
517    mFDs[0].fd = inotify_init();
518    res = inotify_add_watch(mFDs[0].fd, device_path, IN_DELETE | IN_CREATE);
519    if(res < 0) {
520        LOGE("could not add watch for %s, %s\n", device_path, strerror(errno));
521    }
522#else
523    /*
524     * The code in EventHub::getEvent assumes that mFDs[0] is an inotify fd.
525     * We allocate space for it and set it to something invalid.
526     */
527    mFDs[0].fd = -1;
528#endif
529
530    res = scanDir(device_path);
531    if(res < 0) {
532        LOGE("scan dir failed for %s\n", device_path);
533    }
534
535    return true;
536}
537
538// ----------------------------------------------------------------------------
539
540static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
541    const uint8_t* end = array + endIndex;
542    array += startIndex;
543    while (array != end) {
544        if (*(array++) != 0) {
545            return true;
546        }
547    }
548    return false;
549}
550
551static const int32_t GAMEPAD_KEYCODES[] = {
552        AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
553        AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
554        AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
555        AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
556        AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
557        AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE
558};
559
560int EventHub::openDevice(const char *deviceName) {
561    int version;
562    int fd;
563    struct pollfd *new_mFDs;
564    device_t **new_devices;
565    char **new_device_names;
566    char name[80];
567    char location[80];
568    char idstr[80];
569    struct input_id id;
570
571    LOGV("Opening device: %s", deviceName);
572
573    AutoMutex _l(mLock);
574
575    fd = open(deviceName, O_RDWR);
576    if(fd < 0) {
577        LOGE("could not open %s, %s\n", deviceName, strerror(errno));
578        return -1;
579    }
580
581    if(ioctl(fd, EVIOCGVERSION, &version)) {
582        LOGE("could not get driver version for %s, %s\n", deviceName, strerror(errno));
583        return -1;
584    }
585    if(ioctl(fd, EVIOCGID, &id)) {
586        LOGE("could not get driver id for %s, %s\n", deviceName, strerror(errno));
587        return -1;
588    }
589    name[sizeof(name) - 1] = '\0';
590    location[sizeof(location) - 1] = '\0';
591    idstr[sizeof(idstr) - 1] = '\0';
592    if(ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
593        //fprintf(stderr, "could not get device name for %s, %s\n", deviceName, strerror(errno));
594        name[0] = '\0';
595    }
596
597    // check to see if the device is on our excluded list
598    List<String8>::iterator iter = mExcludedDevices.begin();
599    List<String8>::iterator end = mExcludedDevices.end();
600    for ( ; iter != end; iter++) {
601        const char* test = *iter;
602        if (strcmp(name, test) == 0) {
603            LOGI("ignoring event id %s driver %s\n", deviceName, test);
604            close(fd);
605            return -1;
606        }
607    }
608
609    if(ioctl(fd, EVIOCGPHYS(sizeof(location) - 1), &location) < 1) {
610        //fprintf(stderr, "could not get location for %s, %s\n", deviceName, strerror(errno));
611        location[0] = '\0';
612    }
613    if(ioctl(fd, EVIOCGUNIQ(sizeof(idstr) - 1), &idstr) < 1) {
614        //fprintf(stderr, "could not get idstring for %s, %s\n", deviceName, strerror(errno));
615        idstr[0] = '\0';
616    }
617
618    if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
619        LOGE("Error %d making device file descriptor non-blocking.", errno);
620        close(fd);
621        return -1;
622    }
623
624    int devid = 0;
625    while (devid < mNumDevicesById) {
626        if (mDevicesById[devid].device == NULL) {
627            break;
628        }
629        devid++;
630    }
631    if (devid >= mNumDevicesById) {
632        device_ent* new_devids = (device_ent*)realloc(mDevicesById,
633                sizeof(mDevicesById[0]) * (devid + 1));
634        if (new_devids == NULL) {
635            LOGE("out of memory");
636            return -1;
637        }
638        mDevicesById = new_devids;
639        mNumDevicesById = devid+1;
640        mDevicesById[devid].device = NULL;
641        mDevicesById[devid].seq = 0;
642    }
643
644    mDevicesById[devid].seq = (mDevicesById[devid].seq+(1<<SEQ_SHIFT))&SEQ_MASK;
645    if (mDevicesById[devid].seq == 0) {
646        mDevicesById[devid].seq = 1<<SEQ_SHIFT;
647    }
648
649    new_mFDs = (pollfd*)realloc(mFDs, sizeof(mFDs[0]) * (mFDCount + 1));
650    new_devices = (device_t**)realloc(mDevices, sizeof(mDevices[0]) * (mFDCount + 1));
651    if (new_mFDs == NULL || new_devices == NULL) {
652        LOGE("out of memory");
653        return -1;
654    }
655    mFDs = new_mFDs;
656    mDevices = new_devices;
657
658#if 0
659    LOGI("add device %d: %s\n", mFDCount, deviceName);
660    LOGI("  bus:      %04x\n"
661         "  vendor    %04x\n"
662         "  product   %04x\n"
663         "  version   %04x\n",
664        id.bustype, id.vendor, id.product, id.version);
665    LOGI("  name:     \"%s\"\n", name);
666    LOGI("  location: \"%s\"\n"
667         "  id:       \"%s\"\n", location, idstr);
668    LOGI("  version:  %d.%d.%d\n",
669        version >> 16, (version >> 8) & 0xff, version & 0xff);
670#endif
671
672    device_t* device = new device_t(devid|mDevicesById[devid].seq, deviceName, name);
673    if (device == NULL) {
674        LOGE("out of memory");
675        return -1;
676    }
677
678    device->fd = fd;
679    mFDs[mFDCount].fd = fd;
680    mFDs[mFDCount].events = POLLIN;
681    mFDs[mFDCount].revents = 0;
682
683    // Figure out the kinds of events the device reports.
684
685    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
686    memset(key_bitmask, 0, sizeof(key_bitmask));
687
688    LOGV("Getting keys...");
689    if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask) >= 0) {
690        //LOGI("MAP\n");
691        //for (int i = 0; i < sizeof(key_bitmask); i++) {
692        //    LOGI("%d: 0x%02x\n", i, key_bitmask[i]);
693        //}
694
695        // See if this is a keyboard.  Ignore everything in the button range except for
696        // gamepads which are also considered keyboards.
697        if (containsNonZeroByte(key_bitmask, 0, sizeof_bit_array(BTN_MISC))
698                || containsNonZeroByte(key_bitmask, sizeof_bit_array(BTN_GAMEPAD),
699                        sizeof_bit_array(BTN_DIGI))
700                || containsNonZeroByte(key_bitmask, sizeof_bit_array(KEY_OK),
701                        sizeof_bit_array(KEY_MAX + 1))) {
702            device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
703
704            device->keyBitmask = new uint8_t[sizeof(key_bitmask)];
705            if (device->keyBitmask != NULL) {
706                memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask));
707            } else {
708                delete device;
709                LOGE("out of memory allocating key bitmask");
710                return -1;
711            }
712        }
713    }
714
715    // See if this is a trackball (or mouse).
716    if (test_bit(BTN_MOUSE, key_bitmask)) {
717        uint8_t rel_bitmask[sizeof_bit_array(REL_MAX + 1)];
718        memset(rel_bitmask, 0, sizeof(rel_bitmask));
719        LOGV("Getting relative controllers...");
720        if (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bitmask)), rel_bitmask) >= 0) {
721            if (test_bit(REL_X, rel_bitmask) && test_bit(REL_Y, rel_bitmask)) {
722                device->classes |= INPUT_DEVICE_CLASS_TRACKBALL;
723            }
724        }
725    }
726
727    // See if this is a touch pad.
728    uint8_t abs_bitmask[sizeof_bit_array(ABS_MAX + 1)];
729    memset(abs_bitmask, 0, sizeof(abs_bitmask));
730    LOGV("Getting absolute controllers...");
731    if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bitmask)), abs_bitmask) >= 0) {
732        // Is this a new modern multi-touch driver?
733        if (test_bit(ABS_MT_POSITION_X, abs_bitmask)
734                && test_bit(ABS_MT_POSITION_Y, abs_bitmask)) {
735            device->classes |= INPUT_DEVICE_CLASS_TOUCHSCREEN | INPUT_DEVICE_CLASS_TOUCHSCREEN_MT;
736
737        // Is this an old style single-touch driver?
738        } else if (test_bit(BTN_TOUCH, key_bitmask)
739                && test_bit(ABS_X, abs_bitmask) && test_bit(ABS_Y, abs_bitmask)) {
740            device->classes |= INPUT_DEVICE_CLASS_TOUCHSCREEN;
741        }
742    }
743
744#ifdef EV_SW
745    // figure out the switches this device reports
746    uint8_t sw_bitmask[sizeof_bit_array(SW_MAX + 1)];
747    memset(sw_bitmask, 0, sizeof(sw_bitmask));
748    bool hasSwitches = false;
749    if (ioctl(fd, EVIOCGBIT(EV_SW, sizeof(sw_bitmask)), sw_bitmask) >= 0) {
750        for (int i=0; i<EV_SW; i++) {
751            //LOGI("Device 0x%x sw %d: has=%d", device->id, i, test_bit(i, sw_bitmask));
752            if (test_bit(i, sw_bitmask)) {
753                hasSwitches = true;
754                if (mSwitches[i] == 0) {
755                    mSwitches[i] = device->id;
756                }
757            }
758        }
759    }
760    if (hasSwitches) {
761        device->classes |= INPUT_DEVICE_CLASS_SWITCH;
762    }
763#endif
764
765    if ((device->classes & INPUT_DEVICE_CLASS_KEYBOARD) != 0) {
766        char tmpfn[sizeof(name)];
767        char keylayoutFilename[300];
768
769        // a more descriptive name
770        device->name = name;
771
772        // replace all the spaces with underscores
773        strcpy(tmpfn, name);
774        for (char *p = strchr(tmpfn, ' '); p && *p; p = strchr(tmpfn, ' '))
775            *p = '_';
776
777        // find the .kl file we need for this device
778        const char* root = getenv("ANDROID_ROOT");
779        snprintf(keylayoutFilename, sizeof(keylayoutFilename),
780                 "%s/usr/keylayout/%s.kl", root, tmpfn);
781        bool defaultKeymap = false;
782        if (access(keylayoutFilename, R_OK)) {
783            snprintf(keylayoutFilename, sizeof(keylayoutFilename),
784                     "%s/usr/keylayout/%s", root, "qwerty.kl");
785            defaultKeymap = true;
786        }
787        status_t status = device->layoutMap->load(keylayoutFilename);
788        if (status) {
789            LOGE("Error %d loading key layout.", status);
790        }
791
792        // tell the world about the devname (the descriptive name)
793        if (!mHaveFirstKeyboard && !defaultKeymap && strstr(name, "-keypad")) {
794            // the built-in keyboard has a well-known device ID of 0,
795            // this device better not go away.
796            mHaveFirstKeyboard = true;
797            mFirstKeyboardId = device->id;
798            property_set("hw.keyboards.0.devname", name);
799        } else {
800            // ensure mFirstKeyboardId is set to -something-.
801            if (mFirstKeyboardId == 0) {
802                mFirstKeyboardId = device->id;
803            }
804        }
805        char propName[100];
806        sprintf(propName, "hw.keyboards.%u.devname", device->id);
807        property_set(propName, name);
808
809        // 'Q' key support = cheap test of whether this is an alpha-capable kbd
810        if (hasKeycodeLocked(device, AKEYCODE_Q)) {
811            device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
812        }
813
814        // See if this device has a DPAD.
815        if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
816                hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
817                hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
818                hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
819                hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
820            device->classes |= INPUT_DEVICE_CLASS_DPAD;
821        }
822
823        // See if this device has a gamepad.
824        for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
825            if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
826                device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
827                break;
828            }
829        }
830
831        LOGI("New keyboard: device->id=0x%x devname='%s' propName='%s' keylayout='%s'\n",
832                device->id, name, propName, keylayoutFilename);
833    }
834
835    // If the device isn't recognized as something we handle, don't monitor it.
836    if (device->classes == 0) {
837        LOGV("Dropping device %s %p, id = %d\n", deviceName, device, devid);
838        close(fd);
839        delete device;
840        return -1;
841    }
842
843    LOGI("New device: path=%s name=%s id=0x%x (of 0x%x) index=%d fd=%d classes=0x%x\n",
844         deviceName, name, device->id, mNumDevicesById, mFDCount, fd, device->classes);
845
846    LOGV("Adding device %s %p at %d, id = %d, classes = 0x%x\n",
847         deviceName, device, mFDCount, devid, device->classes);
848
849    mDevicesById[devid].device = device;
850    device->next = mOpeningDevices;
851    mOpeningDevices = device;
852    mDevices[mFDCount] = device;
853
854    mFDCount++;
855    return 0;
856}
857
858bool EventHub::hasKeycodeLocked(device_t* device, int keycode) const
859{
860    if (device->keyBitmask == NULL || device->layoutMap == NULL) {
861        return false;
862    }
863
864    Vector<int32_t> scanCodes;
865    device->layoutMap->findScancodes(keycode, &scanCodes);
866    const size_t N = scanCodes.size();
867    for (size_t i=0; i<N && i<=KEY_MAX; i++) {
868        int32_t sc = scanCodes.itemAt(i);
869        if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
870            return true;
871        }
872    }
873
874    return false;
875}
876
877int EventHub::closeDevice(const char *deviceName) {
878    AutoMutex _l(mLock);
879
880    int i;
881    for(i = 1; i < mFDCount; i++) {
882        if(strcmp(mDevices[i]->path.string(), deviceName) == 0) {
883            //LOGD("remove device %d: %s\n", i, deviceName);
884            device_t* device = mDevices[i];
885
886            LOGI("Removed device: path=%s name=%s id=0x%x (of 0x%x) index=%d fd=%d classes=0x%x\n",
887                 device->path.string(), device->name.string(), device->id,
888                 mNumDevicesById, mFDCount, mFDs[i].fd, device->classes);
889
890            // Clear this device's entry.
891            int index = (device->id&ID_MASK);
892            mDevicesById[index].device = NULL;
893
894            // Close the file descriptor and compact the fd array.
895            close(mFDs[i].fd);
896            int count = mFDCount - i - 1;
897            memmove(mDevices + i, mDevices + i + 1, sizeof(mDevices[0]) * count);
898            memmove(mFDs + i, mFDs + i + 1, sizeof(mFDs[0]) * count);
899            mFDCount--;
900
901#ifdef EV_SW
902            for (int j=0; j<EV_SW; j++) {
903                if (mSwitches[j] == device->id) {
904                    mSwitches[j] = 0;
905                }
906            }
907#endif
908
909            device->next = mClosingDevices;
910            mClosingDevices = device;
911
912            if (device->id == mFirstKeyboardId) {
913                LOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
914                        device->path.string(), mFirstKeyboardId);
915                mFirstKeyboardId = 0;
916                property_set("hw.keyboards.0.devname", NULL);
917            }
918            // clear the property
919            char propName[100];
920            sprintf(propName, "hw.keyboards.%u.devname", device->id);
921            property_set(propName, NULL);
922            return 0;
923        }
924    }
925    LOGE("remove device: %s not found\n", deviceName);
926    return -1;
927}
928
929int EventHub::readNotify(int nfd) {
930#ifdef HAVE_INOTIFY
931    int res;
932    char devname[PATH_MAX];
933    char *filename;
934    char event_buf[512];
935    int event_size;
936    int event_pos = 0;
937    struct inotify_event *event;
938
939    LOGV("EventHub::readNotify nfd: %d\n", nfd);
940    res = read(nfd, event_buf, sizeof(event_buf));
941    if(res < (int)sizeof(*event)) {
942        if(errno == EINTR)
943            return 0;
944        LOGW("could not get event, %s\n", strerror(errno));
945        return 1;
946    }
947    //printf("got %d bytes of event information\n", res);
948
949    strcpy(devname, device_path);
950    filename = devname + strlen(devname);
951    *filename++ = '/';
952
953    while(res >= (int)sizeof(*event)) {
954        event = (struct inotify_event *)(event_buf + event_pos);
955        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
956        if(event->len) {
957            strcpy(filename, event->name);
958            if(event->mask & IN_CREATE) {
959                openDevice(devname);
960            }
961            else {
962                closeDevice(devname);
963            }
964        }
965        event_size = sizeof(*event) + event->len;
966        res -= event_size;
967        event_pos += event_size;
968    }
969#endif
970    return 0;
971}
972
973
974int EventHub::scanDir(const char *dirname)
975{
976    char devname[PATH_MAX];
977    char *filename;
978    DIR *dir;
979    struct dirent *de;
980    dir = opendir(dirname);
981    if(dir == NULL)
982        return -1;
983    strcpy(devname, dirname);
984    filename = devname + strlen(devname);
985    *filename++ = '/';
986    while((de = readdir(dir))) {
987        if(de->d_name[0] == '.' &&
988           (de->d_name[1] == '\0' ||
989            (de->d_name[1] == '.' && de->d_name[2] == '\0')))
990            continue;
991        strcpy(filename, de->d_name);
992        openDevice(devname);
993    }
994    closedir(dir);
995    return 0;
996}
997
998void EventHub::dump(String8& dump) {
999    dump.append("Event Hub State:\n");
1000
1001    { // acquire lock
1002        AutoMutex _l(mLock);
1003
1004        dump.appendFormat(INDENT "HaveFirstKeyboard: %s\n", toString(mHaveFirstKeyboard));
1005        dump.appendFormat(INDENT "FirstKeyboardId: 0x%x\n", mFirstKeyboardId);
1006
1007        dump.append(INDENT "Devices:\n");
1008
1009        for (int i = 0; i < mNumDevicesById; i++) {
1010            const device_t* device = mDevicesById[i].device;
1011            if (device) {
1012                if (mFirstKeyboardId == device->id) {
1013                    dump.appendFormat(INDENT2 "0x%x: %s (aka device 0 - first keyboard)\n",
1014                            device->id, device->name.string());
1015                } else {
1016                    dump.appendFormat(INDENT2 "0x%x: %s\n", device->id, device->name.string());
1017                }
1018                dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1019                dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1020                dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n", device->keylayoutFilename.string());
1021            }
1022        }
1023    } // release lock
1024}
1025
1026}; // namespace android
1027