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#define ID_MASK  0x0000ffff
58#define SEQ_MASK 0x7fff0000
59#define SEQ_SHIFT 16
60#define id_to_index(id)         ((id&ID_MASK)+1)
61
62#ifndef ABS_MT_TOUCH_MAJOR
63#define ABS_MT_TOUCH_MAJOR      0x30    /* Major axis of touching ellipse */
64#endif
65
66#ifndef ABS_MT_POSITION_X
67#define ABS_MT_POSITION_X       0x35    /* Center X ellipse position */
68#endif
69
70#ifndef ABS_MT_POSITION_Y
71#define ABS_MT_POSITION_Y       0x36    /* Center Y ellipse position */
72#endif
73
74namespace android {
75
76static const char *WAKE_LOCK_ID = "KeyEvents";
77static const char *device_path = "/dev/input";
78
79/* return the larger integer */
80static inline int max(int v1, int v2)
81{
82    return (v1 > v2) ? v1 : v2;
83}
84
85EventHub::device_t::device_t(int32_t _id, const char* _path, const char* name)
86    : id(_id), path(_path), name(name), classes(0)
87    , keyBitmask(NULL), layoutMap(new KeyLayoutMap()), next(NULL) {
88}
89
90EventHub::device_t::~device_t() {
91    delete [] keyBitmask;
92    delete layoutMap;
93}
94
95EventHub::EventHub(void)
96    : mError(NO_INIT), mHaveFirstKeyboard(false), mFirstKeyboardId(0)
97    , mDevicesById(0), mNumDevicesById(0)
98    , mOpeningDevices(0), mClosingDevices(0)
99    , mDevices(0), mFDs(0), mFDCount(0), mOpened(false)
100{
101    acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
102#ifdef EV_SW
103    memset(mSwitches, 0, sizeof(mSwitches));
104#endif
105}
106
107/*
108 * Clean up.
109 */
110EventHub::~EventHub(void)
111{
112    release_wake_lock(WAKE_LOCK_ID);
113    // we should free stuff here...
114}
115
116status_t EventHub::errorCheck() const
117{
118    return mError;
119}
120
121String8 EventHub::getDeviceName(int32_t deviceId) const
122{
123    AutoMutex _l(mLock);
124    device_t* device = getDevice(deviceId);
125    if (device == NULL) return String8();
126    return device->name;
127}
128
129uint32_t EventHub::getDeviceClasses(int32_t deviceId) const
130{
131    AutoMutex _l(mLock);
132    device_t* device = getDevice(deviceId);
133    if (device == NULL) return 0;
134    return device->classes;
135}
136
137int EventHub::getAbsoluteInfo(int32_t deviceId, int axis, int *outMinValue,
138        int* outMaxValue, int* outFlat, int* outFuzz) const
139{
140    AutoMutex _l(mLock);
141    device_t* device = getDevice(deviceId);
142    if (device == NULL) return -1;
143
144    struct input_absinfo info;
145
146    if(ioctl(mFDs[id_to_index(device->id)].fd, EVIOCGABS(axis), &info)) {
147        LOGE("Error reading absolute controller %d for device %s fd %d\n",
148             axis, device->name.string(), mFDs[id_to_index(device->id)].fd);
149        return -1;
150    }
151    *outMinValue = info.minimum;
152    *outMaxValue = info.maximum;
153    *outFlat = info.flat;
154    *outFuzz = info.fuzz;
155    return 0;
156}
157
158int EventHub::getSwitchState(int sw) const
159{
160#ifdef EV_SW
161    if (sw >= 0 && sw <= SW_MAX) {
162        int32_t devid = mSwitches[sw];
163        if (devid != 0) {
164            return getSwitchState(devid, sw);
165        }
166    }
167#endif
168    return -1;
169}
170
171int EventHub::getSwitchState(int32_t deviceId, int sw) const
172{
173#ifdef EV_SW
174    AutoMutex _l(mLock);
175    device_t* device = getDevice(deviceId);
176    if (device == NULL) return -1;
177
178    if (sw >= 0 && sw <= SW_MAX) {
179        uint8_t sw_bitmask[(SW_MAX+7)/8];
180        memset(sw_bitmask, 0, sizeof(sw_bitmask));
181        if (ioctl(mFDs[id_to_index(device->id)].fd,
182                   EVIOCGSW(sizeof(sw_bitmask)), sw_bitmask) >= 0) {
183            return test_bit(sw, sw_bitmask) ? 1 : 0;
184        }
185    }
186#endif
187
188    return -1;
189}
190
191int EventHub::getScancodeState(int code) const
192{
193    return getScancodeState(mFirstKeyboardId, code);
194}
195
196int EventHub::getScancodeState(int32_t deviceId, int code) const
197{
198    AutoMutex _l(mLock);
199    device_t* device = getDevice(deviceId);
200    if (device == NULL) return -1;
201
202    if (code >= 0 && code <= KEY_MAX) {
203        uint8_t key_bitmask[(KEY_MAX+7)/8];
204        memset(key_bitmask, 0, sizeof(key_bitmask));
205        if (ioctl(mFDs[id_to_index(device->id)].fd,
206                   EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
207            return test_bit(code, key_bitmask) ? 1 : 0;
208        }
209    }
210
211    return -1;
212}
213
214int EventHub::getKeycodeState(int code) const
215{
216    return getKeycodeState(mFirstKeyboardId, code);
217}
218
219int EventHub::getKeycodeState(int32_t deviceId, int code) const
220{
221    AutoMutex _l(mLock);
222    device_t* device = getDevice(deviceId);
223    if (device == NULL || device->layoutMap == NULL) return -1;
224
225    Vector<int32_t> scanCodes;
226    device->layoutMap->findScancodes(code, &scanCodes);
227
228    uint8_t key_bitmask[(KEY_MAX+7)/8];
229    memset(key_bitmask, 0, sizeof(key_bitmask));
230    if (ioctl(mFDs[id_to_index(device->id)].fd,
231               EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
232        #if 0
233        for (size_t i=0; i<=KEY_MAX; i++) {
234            LOGI("(Scan code %d: down=%d)", i, test_bit(i, key_bitmask));
235        }
236        #endif
237        const size_t N = scanCodes.size();
238        for (size_t i=0; i<N && i<=KEY_MAX; i++) {
239            int32_t sc = scanCodes.itemAt(i);
240            //LOGI("Code %d: down=%d", sc, test_bit(sc, key_bitmask));
241            if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, key_bitmask)) {
242                return 1;
243            }
244        }
245    }
246
247    return 0;
248}
249
250status_t EventHub::scancodeToKeycode(int32_t deviceId, int scancode,
251        int32_t* outKeycode, uint32_t* outFlags) const
252{
253    AutoMutex _l(mLock);
254    device_t* device = getDevice(deviceId);
255
256    if (device != NULL && device->layoutMap != NULL) {
257        status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
258        if (err == NO_ERROR) {
259            return NO_ERROR;
260        }
261    }
262
263    if (mHaveFirstKeyboard) {
264        device = getDevice(mFirstKeyboardId);
265
266        if (device != NULL && device->layoutMap != NULL) {
267            status_t err = device->layoutMap->map(scancode, outKeycode, outFlags);
268            if (err == NO_ERROR) {
269                return NO_ERROR;
270            }
271        }
272    }
273
274    *outKeycode = 0;
275    *outFlags = 0;
276    return NAME_NOT_FOUND;
277}
278
279void EventHub::addExcludedDevice(const char* deviceName)
280{
281    String8 name(deviceName);
282    mExcludedDevices.push_back(name);
283}
284
285EventHub::device_t* EventHub::getDevice(int32_t deviceId) const
286{
287    if (deviceId == 0) deviceId = mFirstKeyboardId;
288    int32_t id = deviceId & ID_MASK;
289    if (id >= mNumDevicesById || id < 0) return NULL;
290    device_t* dev = mDevicesById[id].device;
291    if (dev == NULL) return NULL;
292    if (dev->id == deviceId) {
293        return dev;
294    }
295    return NULL;
296}
297
298bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType,
299        int32_t* outScancode, int32_t* outKeycode, uint32_t *outFlags,
300        int32_t* outValue, nsecs_t* outWhen)
301{
302    *outDeviceId = 0;
303    *outType = 0;
304    *outScancode = 0;
305    *outKeycode = 0;
306    *outFlags = 0;
307    *outValue = 0;
308    *outWhen = 0;
309
310    status_t err;
311
312    fd_set readfds;
313    int maxFd = -1;
314    int cc;
315    int i;
316    int res;
317    int pollres;
318    struct input_event iev;
319
320    // Note that we only allow one caller to getEvent(), so don't need
321    // to do locking here...  only when adding/removing devices.
322
323    if (!mOpened) {
324        mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;
325        mOpened = true;
326    }
327
328    while(1) {
329
330        // First, report any devices that had last been added/removed.
331        if (mClosingDevices != NULL) {
332            device_t* device = mClosingDevices;
333            LOGV("Reporting device closed: id=0x%x, name=%s\n",
334                 device->id, device->path.string());
335            mClosingDevices = device->next;
336            *outDeviceId = device->id;
337            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
338            *outType = DEVICE_REMOVED;
339            delete device;
340            return true;
341        }
342        if (mOpeningDevices != NULL) {
343            device_t* device = mOpeningDevices;
344            LOGV("Reporting device opened: id=0x%x, name=%s\n",
345                 device->id, device->path.string());
346            mOpeningDevices = device->next;
347            *outDeviceId = device->id;
348            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
349            *outType = DEVICE_ADDED;
350            return true;
351        }
352
353        release_wake_lock(WAKE_LOCK_ID);
354
355        pollres = poll(mFDs, mFDCount, -1);
356
357        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
358
359        if (pollres <= 0) {
360            if (errno != EINTR) {
361                LOGW("select failed (errno=%d)\n", errno);
362                usleep(100000);
363            }
364            continue;
365        }
366
367        //printf("poll %d, returned %d\n", mFDCount, pollres);
368
369        // mFDs[0] is used for inotify, so process regular events starting at mFDs[1]
370        for(i = 1; i < mFDCount; i++) {
371            if(mFDs[i].revents) {
372                LOGV("revents for %d = 0x%08x", i, mFDs[i].revents);
373                if(mFDs[i].revents & POLLIN) {
374                    res = read(mFDs[i].fd, &iev, sizeof(iev));
375                    if (res == sizeof(iev)) {
376                        LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d",
377                             mDevices[i]->path.string(),
378                             (int) iev.time.tv_sec, (int) iev.time.tv_usec,
379                             iev.type, iev.code, iev.value);
380                        *outDeviceId = mDevices[i]->id;
381                        if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
382                        *outType = iev.type;
383                        *outScancode = iev.code;
384                        if (iev.type == EV_KEY) {
385                            err = mDevices[i]->layoutMap->map(iev.code, outKeycode, outFlags);
386                            LOGV("iev.code=%d outKeycode=%d outFlags=0x%08x err=%d\n",
387                                iev.code, *outKeycode, *outFlags, err);
388                            if (err != 0) {
389                                *outKeycode = 0;
390                                *outFlags = 0;
391                            }
392                        } else {
393                            *outKeycode = iev.code;
394                        }
395                        *outValue = iev.value;
396                        *outWhen = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);
397                        return true;
398                    } else {
399                        if (res<0) {
400                            LOGW("could not get event (errno=%d)", errno);
401                        } else {
402                            LOGE("could not get event (wrong size: %d)", res);
403                        }
404                        continue;
405                    }
406                }
407            }
408        }
409
410        // read_notify() will modify mFDs and mFDCount, so this must be done after
411        // processing all other events.
412        if(mFDs[0].revents & POLLIN) {
413            read_notify(mFDs[0].fd);
414        }
415    }
416}
417
418/*
419 * Open the platform-specific input device.
420 */
421bool EventHub::openPlatformInput(void)
422{
423    /*
424     * Open platform-specific input device(s).
425     */
426    int res;
427
428    mFDCount = 1;
429    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));
430    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));
431    mFDs[0].events = POLLIN;
432    mDevices[0] = NULL;
433#ifdef HAVE_INOTIFY
434    mFDs[0].fd = inotify_init();
435    res = inotify_add_watch(mFDs[0].fd, device_path, IN_DELETE | IN_CREATE);
436    if(res < 0) {
437        LOGE("could not add watch for %s, %s\n", device_path, strerror(errno));
438    }
439#else
440    /*
441     * The code in EventHub::getEvent assumes that mFDs[0] is an inotify fd.
442     * We allocate space for it and set it to something invalid.
443     */
444    mFDs[0].fd = -1;
445#endif
446
447    res = scan_dir(device_path);
448    if(res < 0) {
449        LOGE("scan dir failed for %s\n", device_path);
450        //open_device("/dev/input/event0");
451    }
452
453    return true;
454}
455
456/*
457 * Inspect the known devices to determine whether physical keys exist for the given
458 * framework-domain key codes.
459 */
460bool EventHub::hasKeys(size_t numCodes, int32_t* keyCodes, uint8_t* outFlags) {
461    for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
462        outFlags[codeIndex] = 0;
463
464        // check each available hardware device for support for this keycode
465        Vector<int32_t> scanCodes;
466        for (int n = 0; (n < mFDCount) && (outFlags[codeIndex] == 0); n++) {
467            if (mDevices[n]) {
468                status_t err = mDevices[n]->layoutMap->findScancodes(keyCodes[codeIndex], &scanCodes);
469                if (!err) {
470                    // check the possible scan codes identified by the layout map against the
471                    // map of codes actually emitted by the driver
472                    for (size_t sc = 0; sc < scanCodes.size(); sc++) {
473                        if (test_bit(scanCodes[sc], mDevices[n]->keyBitmask)) {
474                            outFlags[codeIndex] = 1;
475                            break;
476                        }
477                    }
478                }
479            }
480        }
481    }
482
483    return true;
484}
485
486// ----------------------------------------------------------------------------
487
488int EventHub::open_device(const char *deviceName)
489{
490    int version;
491    int fd;
492    struct pollfd *new_mFDs;
493    device_t **new_devices;
494    char **new_device_names;
495    char name[80];
496    char location[80];
497    char idstr[80];
498    struct input_id id;
499
500    LOGV("Opening device: %s", deviceName);
501
502    AutoMutex _l(mLock);
503
504    fd = open(deviceName, O_RDWR);
505    if(fd < 0) {
506        LOGE("could not open %s, %s\n", deviceName, strerror(errno));
507        return -1;
508    }
509
510    if(ioctl(fd, EVIOCGVERSION, &version)) {
511        LOGE("could not get driver version for %s, %s\n", deviceName, strerror(errno));
512        return -1;
513    }
514    if(ioctl(fd, EVIOCGID, &id)) {
515        LOGE("could not get driver id for %s, %s\n", deviceName, strerror(errno));
516        return -1;
517    }
518    name[sizeof(name) - 1] = '\0';
519    location[sizeof(location) - 1] = '\0';
520    idstr[sizeof(idstr) - 1] = '\0';
521    if(ioctl(fd, EVIOCGNAME(sizeof(name) - 1), &name) < 1) {
522        //fprintf(stderr, "could not get device name for %s, %s\n", deviceName, strerror(errno));
523        name[0] = '\0';
524    }
525
526    // check to see if the device is on our excluded list
527    List<String8>::iterator iter = mExcludedDevices.begin();
528    List<String8>::iterator end = mExcludedDevices.end();
529    for ( ; iter != end; iter++) {
530        const char* test = *iter;
531        if (strcmp(name, test) == 0) {
532            LOGI("ignoring event id %s driver %s\n", deviceName, test);
533            close(fd);
534            fd = -1;
535            return -1;
536        }
537    }
538
539    if(ioctl(fd, EVIOCGPHYS(sizeof(location) - 1), &location) < 1) {
540        //fprintf(stderr, "could not get location for %s, %s\n", deviceName, strerror(errno));
541        location[0] = '\0';
542    }
543    if(ioctl(fd, EVIOCGUNIQ(sizeof(idstr) - 1), &idstr) < 1) {
544        //fprintf(stderr, "could not get idstring for %s, %s\n", deviceName, strerror(errno));
545        idstr[0] = '\0';
546    }
547
548    int devid = 0;
549    while (devid < mNumDevicesById) {
550        if (mDevicesById[devid].device == NULL) {
551            break;
552        }
553        devid++;
554    }
555    if (devid >= mNumDevicesById) {
556        device_ent* new_devids = (device_ent*)realloc(mDevicesById,
557                sizeof(mDevicesById[0]) * (devid + 1));
558        if (new_devids == NULL) {
559            LOGE("out of memory");
560            return -1;
561        }
562        mDevicesById = new_devids;
563        mNumDevicesById = devid+1;
564        mDevicesById[devid].device = NULL;
565        mDevicesById[devid].seq = 0;
566    }
567
568    mDevicesById[devid].seq = (mDevicesById[devid].seq+(1<<SEQ_SHIFT))&SEQ_MASK;
569    if (mDevicesById[devid].seq == 0) {
570        mDevicesById[devid].seq = 1<<SEQ_SHIFT;
571    }
572
573    new_mFDs = (pollfd*)realloc(mFDs, sizeof(mFDs[0]) * (mFDCount + 1));
574    new_devices = (device_t**)realloc(mDevices, sizeof(mDevices[0]) * (mFDCount + 1));
575    if (new_mFDs == NULL || new_devices == NULL) {
576        LOGE("out of memory");
577        return -1;
578    }
579    mFDs = new_mFDs;
580    mDevices = new_devices;
581
582#if 0
583    LOGI("add device %d: %s\n", mFDCount, deviceName);
584    LOGI("  bus:      %04x\n"
585         "  vendor    %04x\n"
586         "  product   %04x\n"
587         "  version   %04x\n",
588        id.bustype, id.vendor, id.product, id.version);
589    LOGI("  name:     \"%s\"\n", name);
590    LOGI("  location: \"%s\"\n"
591         "  id:       \"%s\"\n", location, idstr);
592    LOGI("  version:  %d.%d.%d\n",
593        version >> 16, (version >> 8) & 0xff, version & 0xff);
594#endif
595
596    device_t* device = new device_t(devid|mDevicesById[devid].seq, deviceName, name);
597    if (device == NULL) {
598        LOGE("out of memory");
599        return -1;
600    }
601
602    mFDs[mFDCount].fd = fd;
603    mFDs[mFDCount].events = POLLIN;
604
605    // figure out the kinds of events the device reports
606
607    // See if this is a keyboard, and classify it.  Note that we only
608    // consider up through the function keys; we don't want to include
609    // ones after that (play cd etc) so we don't mistakenly consider a
610    // controller to be a keyboard.
611    uint8_t key_bitmask[(KEY_MAX+7)/8];
612    memset(key_bitmask, 0, sizeof(key_bitmask));
613    LOGV("Getting keys...");
614    if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask) >= 0) {
615        //LOGI("MAP\n");
616        //for (int i=0; i<((KEY_MAX+7)/8); i++) {
617        //    LOGI("%d: 0x%02x\n", i, key_bitmask[i]);
618        //}
619        for (int i=0; i<((BTN_MISC+7)/8); i++) {
620            if (key_bitmask[i] != 0) {
621                device->classes |= CLASS_KEYBOARD;
622                break;
623            }
624        }
625        if ((device->classes & CLASS_KEYBOARD) != 0) {
626            device->keyBitmask = new uint8_t[sizeof(key_bitmask)];
627            if (device->keyBitmask != NULL) {
628                memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask));
629            } else {
630                delete device;
631                LOGE("out of memory allocating key bitmask");
632                return -1;
633            }
634        }
635    }
636
637    // See if this is a trackball.
638    if (test_bit(BTN_MOUSE, key_bitmask)) {
639        uint8_t rel_bitmask[(REL_MAX+7)/8];
640        memset(rel_bitmask, 0, sizeof(rel_bitmask));
641        LOGV("Getting relative controllers...");
642        if (ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bitmask)), rel_bitmask) >= 0)
643        {
644            if (test_bit(REL_X, rel_bitmask) && test_bit(REL_Y, rel_bitmask)) {
645                device->classes |= CLASS_TRACKBALL;
646            }
647        }
648    }
649
650    uint8_t abs_bitmask[(ABS_MAX+7)/8];
651    memset(abs_bitmask, 0, sizeof(abs_bitmask));
652    LOGV("Getting absolute controllers...");
653    ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bitmask)), abs_bitmask);
654
655    // Is this a new modern multi-touch driver?
656    if (test_bit(ABS_MT_TOUCH_MAJOR, abs_bitmask)
657            && test_bit(ABS_MT_POSITION_X, abs_bitmask)
658            && test_bit(ABS_MT_POSITION_Y, abs_bitmask)) {
659        device->classes |= CLASS_TOUCHSCREEN | CLASS_TOUCHSCREEN_MT;
660
661    // Is this an old style single-touch driver?
662    } else if (test_bit(BTN_TOUCH, key_bitmask)
663            && test_bit(ABS_X, abs_bitmask) && test_bit(ABS_Y, abs_bitmask)) {
664        device->classes |= CLASS_TOUCHSCREEN;
665    }
666
667#ifdef EV_SW
668    // figure out the switches this device reports
669    uint8_t sw_bitmask[(SW_MAX+7)/8];
670    memset(sw_bitmask, 0, sizeof(sw_bitmask));
671    if (ioctl(fd, EVIOCGBIT(EV_SW, sizeof(sw_bitmask)), sw_bitmask) >= 0) {
672        for (int i=0; i<EV_SW; i++) {
673            //LOGI("Device 0x%x sw %d: has=%d", device->id, i, test_bit(i, sw_bitmask));
674            if (test_bit(i, sw_bitmask)) {
675                if (mSwitches[i] == 0) {
676                    mSwitches[i] = device->id;
677                }
678            }
679        }
680    }
681#endif
682
683    if ((device->classes&CLASS_KEYBOARD) != 0) {
684        char tmpfn[sizeof(name)];
685        char keylayoutFilename[300];
686
687        // a more descriptive name
688        device->name = name;
689
690        // replace all the spaces with underscores
691        strcpy(tmpfn, name);
692        for (char *p = strchr(tmpfn, ' '); p && *p; p = strchr(tmpfn, ' '))
693            *p = '_';
694
695        // find the .kl file we need for this device
696        const char* root = getenv("ANDROID_ROOT");
697        snprintf(keylayoutFilename, sizeof(keylayoutFilename),
698                 "%s/usr/keylayout/%s.kl", root, tmpfn);
699        bool defaultKeymap = false;
700        if (access(keylayoutFilename, R_OK)) {
701            snprintf(keylayoutFilename, sizeof(keylayoutFilename),
702                     "%s/usr/keylayout/%s", root, "qwerty.kl");
703            defaultKeymap = true;
704        }
705        device->layoutMap->load(keylayoutFilename);
706
707        // tell the world about the devname (the descriptive name)
708        if (!mHaveFirstKeyboard && !defaultKeymap && strstr(name, "-keypad")) {
709            // the built-in keyboard has a well-known device ID of 0,
710            // this device better not go away.
711            mHaveFirstKeyboard = true;
712            mFirstKeyboardId = device->id;
713            property_set("hw.keyboards.0.devname", name);
714        } else {
715            // ensure mFirstKeyboardId is set to -something-.
716            if (mFirstKeyboardId == 0) {
717                mFirstKeyboardId = device->id;
718            }
719        }
720        char propName[100];
721        sprintf(propName, "hw.keyboards.%u.devname", device->id);
722        property_set(propName, name);
723
724        // 'Q' key support = cheap test of whether this is an alpha-capable kbd
725        if (hasKeycode(device, kKeyCodeQ)) {
726            device->classes |= CLASS_ALPHAKEY;
727        }
728
729        // See if this has a DPAD.
730        if (hasKeycode(device, kKeyCodeDpadUp) &&
731                hasKeycode(device, kKeyCodeDpadDown) &&
732                hasKeycode(device, kKeyCodeDpadLeft) &&
733                hasKeycode(device, kKeyCodeDpadRight) &&
734                hasKeycode(device, kKeyCodeDpadCenter)) {
735            device->classes |= CLASS_DPAD;
736        }
737
738        LOGI("New keyboard: device->id=0x%x devname='%s' propName='%s' keylayout='%s'\n",
739                device->id, name, propName, keylayoutFilename);
740    }
741
742    LOGI("New device: path=%s name=%s id=0x%x (of 0x%x) index=%d fd=%d classes=0x%x\n",
743         deviceName, name, device->id, mNumDevicesById, mFDCount, fd, device->classes);
744
745    LOGV("Adding device %s %p at %d, id = %d, classes = 0x%x\n",
746         deviceName, device, mFDCount, devid, device->classes);
747
748    mDevicesById[devid].device = device;
749    device->next = mOpeningDevices;
750    mOpeningDevices = device;
751    mDevices[mFDCount] = device;
752
753    mFDCount++;
754    return 0;
755}
756
757bool EventHub::hasKeycode(device_t* device, int keycode) const
758{
759    if (device->keyBitmask == NULL || device->layoutMap == NULL) {
760        return false;
761    }
762
763    Vector<int32_t> scanCodes;
764    device->layoutMap->findScancodes(keycode, &scanCodes);
765    const size_t N = scanCodes.size();
766    for (size_t i=0; i<N && i<=KEY_MAX; i++) {
767        int32_t sc = scanCodes.itemAt(i);
768        if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
769            return true;
770        }
771    }
772
773    return false;
774}
775
776int EventHub::close_device(const char *deviceName)
777{
778    AutoMutex _l(mLock);
779
780    int i;
781    for(i = 1; i < mFDCount; i++) {
782        if(strcmp(mDevices[i]->path.string(), deviceName) == 0) {
783            //LOGD("remove device %d: %s\n", i, deviceName);
784            device_t* device = mDevices[i];
785
786            LOGI("Removed device: path=%s name=%s id=0x%x (of 0x%x) index=%d fd=%d classes=0x%x\n",
787                 device->path.string(), device->name.string(), device->id,
788                 mNumDevicesById, mFDCount, mFDs[i].fd, device->classes);
789
790            // Clear this device's entry.
791            int index = (device->id&ID_MASK);
792            mDevicesById[index].device = NULL;
793
794            // Close the file descriptor and compact the fd array.
795            close(mFDs[i].fd);
796            int count = mFDCount - i - 1;
797            memmove(mDevices + i, mDevices + i + 1, sizeof(mDevices[0]) * count);
798            memmove(mFDs + i, mFDs + i + 1, sizeof(mFDs[0]) * count);
799            mFDCount--;
800
801#ifdef EV_SW
802            for (int j=0; j<EV_SW; j++) {
803                if (mSwitches[j] == device->id) {
804                    mSwitches[j] = 0;
805                }
806            }
807#endif
808
809            device->next = mClosingDevices;
810            mClosingDevices = device;
811
812            if (device->id == mFirstKeyboardId) {
813                LOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
814                        device->path.string(), mFirstKeyboardId);
815                mFirstKeyboardId = 0;
816                property_set("hw.keyboards.0.devname", NULL);
817            }
818            // clear the property
819            char propName[100];
820            sprintf(propName, "hw.keyboards.%u.devname", device->id);
821            property_set(propName, NULL);
822            return 0;
823        }
824    }
825    LOGE("remove device: %s not found\n", deviceName);
826    return -1;
827}
828
829int EventHub::read_notify(int nfd)
830{
831#ifdef HAVE_INOTIFY
832    int res;
833    char devname[PATH_MAX];
834    char *filename;
835    char event_buf[512];
836    int event_size;
837    int event_pos = 0;
838    struct inotify_event *event;
839
840    LOGV("EventHub::read_notify nfd: %d\n", nfd);
841    res = read(nfd, event_buf, sizeof(event_buf));
842    if(res < (int)sizeof(*event)) {
843        if(errno == EINTR)
844            return 0;
845        LOGW("could not get event, %s\n", strerror(errno));
846        return 1;
847    }
848    //printf("got %d bytes of event information\n", res);
849
850    strcpy(devname, device_path);
851    filename = devname + strlen(devname);
852    *filename++ = '/';
853
854    while(res >= (int)sizeof(*event)) {
855        event = (struct inotify_event *)(event_buf + event_pos);
856        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
857        if(event->len) {
858            strcpy(filename, event->name);
859            if(event->mask & IN_CREATE) {
860                open_device(devname);
861            }
862            else {
863                close_device(devname);
864            }
865        }
866        event_size = sizeof(*event) + event->len;
867        res -= event_size;
868        event_pos += event_size;
869    }
870#endif
871    return 0;
872}
873
874
875int EventHub::scan_dir(const char *dirname)
876{
877    char devname[PATH_MAX];
878    char *filename;
879    DIR *dir;
880    struct dirent *de;
881    dir = opendir(dirname);
882    if(dir == NULL)
883        return -1;
884    strcpy(devname, dirname);
885    filename = devname + strlen(devname);
886    *filename++ = '/';
887    while((de = readdir(dir))) {
888        if(de->d_name[0] == '.' &&
889           (de->d_name[1] == '\0' ||
890            (de->d_name[1] == '.' && de->d_name[2] == '\0')))
891            continue;
892        strcpy(filename, de->d_name);
893        open_device(devname);
894    }
895    closedir(dir);
896    return 0;
897}
898
899}; // namespace android
900