EventHub.cpp revision 68d6075b4ad2205c10064c78cde552e3210cca91
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// Handle events, like key input and vsync.
19//
20// The goal is to provide an optimized solution for Linux, not an
21// implementation that works well across all platforms.  We expect
22// events to arrive on file descriptors, so that we can use a select()
23// select() call to sleep.
24//
25// We can't select() on anything but network sockets in Windows, so we
26// provide an alternative implementation of waitEvent for that platform.
27//
28#define LOG_TAG "EventHub"
29
30//#define LOG_NDEBUG 0
31
32#include "EventHub.h"
33
34#include <hardware_legacy/power.h>
35
36#include <cutils/properties.h>
37#include <utils/Log.h>
38#include <utils/Timers.h>
39#include <utils/threads.h>
40#include <utils/Errors.h>
41
42#include <stdlib.h>
43#include <stdio.h>
44#include <unistd.h>
45#include <fcntl.h>
46#include <memory.h>
47#include <errno.h>
48#include <assert.h>
49
50#include <ui/KeyLayoutMap.h>
51#include <ui/KeyCharacterMap.h>
52#include <ui/VirtualKeyMap.h>
53
54#include <string.h>
55#include <stdint.h>
56#include <dirent.h>
57#ifdef HAVE_INOTIFY
58# include <sys/inotify.h>
59#endif
60#ifdef HAVE_ANDROID_OS
61# include <sys/limits.h>        /* not part of Linux */
62#endif
63#include <sys/poll.h>
64#include <sys/ioctl.h>
65
66/* this macro is used to tell if "bit" is set in "array"
67 * it selects a byte from the array, and does a boolean AND
68 * operation with a byte that only has the relevant bit set.
69 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
70 */
71#define test_bit(bit, array)    (array[bit/8] & (1<<(bit%8)))
72
73/* this macro computes the number of bytes needed to represent a bit array of the specified size */
74#define sizeof_bit_array(bits)  ((bits + 7) / 8)
75
76// Fd at index 0 is always reserved for inotify
77#define FIRST_ACTUAL_DEVICE_INDEX 1
78
79#define INDENT "  "
80#define INDENT2 "    "
81#define INDENT3 "      "
82
83namespace android {
84
85static const char *WAKE_LOCK_ID = "KeyEvents";
86static const char *DEVICE_PATH = "/dev/input";
87
88/* return the larger integer */
89static inline int max(int v1, int v2)
90{
91    return (v1 > v2) ? v1 : v2;
92}
93
94static inline const char* toString(bool value) {
95    return value ? "true" : "false";
96}
97
98// --- EventHub::Device ---
99
100EventHub::Device::Device(int fd, int32_t id, const String8& path,
101        const InputDeviceIdentifier& identifier) :
102        next(NULL),
103        fd(fd), id(id), path(path), identifier(identifier),
104        classes(0), keyBitmask(NULL), relBitmask(NULL),
105        configuration(NULL), virtualKeyMap(NULL) {
106}
107
108EventHub::Device::~Device() {
109    close();
110    delete[] keyBitmask;
111    delete[] relBitmask;
112    delete configuration;
113    delete virtualKeyMap;
114}
115
116void EventHub::Device::close() {
117    if (fd >= 0) {
118        ::close(fd);
119        fd = -1;
120    }
121}
122
123
124// --- EventHub ---
125
126EventHub::EventHub(void) :
127        mError(NO_INIT), mBuiltInKeyboardId(-1), mNextDeviceId(1),
128        mOpeningDevices(0), mClosingDevices(0),
129        mOpened(false), mNeedToSendFinishedDeviceScan(false),
130        mInputBufferIndex(0), mInputBufferCount(0), mInputFdIndex(0) {
131    acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
132    memset(mSwitches, 0, sizeof(mSwitches));
133}
134
135EventHub::~EventHub(void) {
136    release_wake_lock(WAKE_LOCK_ID);
137    // we should free stuff here...
138}
139
140status_t EventHub::errorCheck() const {
141    return mError;
142}
143
144String8 EventHub::getDeviceName(int32_t deviceId) const {
145    AutoMutex _l(mLock);
146    Device* device = getDeviceLocked(deviceId);
147    if (device == NULL) return String8();
148    return device->identifier.name;
149}
150
151uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
152    AutoMutex _l(mLock);
153    Device* device = getDeviceLocked(deviceId);
154    if (device == NULL) return 0;
155    return device->classes;
156}
157
158void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
159    AutoMutex _l(mLock);
160    Device* device = getDeviceLocked(deviceId);
161    if (device && device->configuration) {
162        *outConfiguration = *device->configuration;
163    } else {
164        outConfiguration->clear();
165    }
166}
167
168status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
169        RawAbsoluteAxisInfo* outAxisInfo) const {
170    outAxisInfo->clear();
171
172    AutoMutex _l(mLock);
173    Device* device = getDeviceLocked(deviceId);
174    if (device == NULL) return -1;
175
176    struct input_absinfo info;
177
178    if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
179        LOGW("Error reading absolute controller %d for device %s fd %d\n",
180             axis, device->identifier.name.string(), device->fd);
181        return -errno;
182    }
183
184    if (info.minimum != info.maximum) {
185        outAxisInfo->valid = true;
186        outAxisInfo->minValue = info.minimum;
187        outAxisInfo->maxValue = info.maximum;
188        outAxisInfo->flat = info.flat;
189        outAxisInfo->fuzz = info.fuzz;
190    }
191    return OK;
192}
193
194bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
195    if (axis >= 0 && axis <= REL_MAX) {
196        AutoMutex _l(mLock);
197
198        Device* device = getDeviceLocked(deviceId);
199        if (device && device->relBitmask) {
200            return test_bit(axis, device->relBitmask);
201        }
202    }
203    return false;
204}
205
206int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
207    if (scanCode >= 0 && scanCode <= KEY_MAX) {
208        AutoMutex _l(mLock);
209
210        Device* device = getDeviceLocked(deviceId);
211        if (device != NULL) {
212            return getScanCodeStateLocked(device, scanCode);
213        }
214    }
215    return AKEY_STATE_UNKNOWN;
216}
217
218int32_t EventHub::getScanCodeStateLocked(Device* device, int32_t scanCode) const {
219    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
220    memset(key_bitmask, 0, sizeof(key_bitmask));
221    if (ioctl(device->fd,
222               EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
223        return test_bit(scanCode, key_bitmask) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
224    }
225    return AKEY_STATE_UNKNOWN;
226}
227
228int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
229    AutoMutex _l(mLock);
230
231    Device* device = getDeviceLocked(deviceId);
232    if (device != NULL) {
233        return getKeyCodeStateLocked(device, keyCode);
234    }
235    return AKEY_STATE_UNKNOWN;
236}
237
238int32_t EventHub::getKeyCodeStateLocked(Device* device, int32_t keyCode) const {
239    if (!device->keyMap.haveKeyLayout()) {
240        return AKEY_STATE_UNKNOWN;
241    }
242
243    Vector<int32_t> scanCodes;
244    device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
245
246    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
247    memset(key_bitmask, 0, sizeof(key_bitmask));
248    if (ioctl(device->fd, EVIOCGKEY(sizeof(key_bitmask)), key_bitmask) >= 0) {
249        #if 0
250        for (size_t i=0; i<=KEY_MAX; i++) {
251            LOGI("(Scan code %d: down=%d)", i, test_bit(i, key_bitmask));
252        }
253        #endif
254        const size_t N = scanCodes.size();
255        for (size_t i=0; i<N && i<=KEY_MAX; i++) {
256            int32_t sc = scanCodes.itemAt(i);
257            //LOGI("Code %d: down=%d", sc, test_bit(sc, key_bitmask));
258            if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, key_bitmask)) {
259                return AKEY_STATE_DOWN;
260            }
261        }
262        return AKEY_STATE_UP;
263    }
264    return AKEY_STATE_UNKNOWN;
265}
266
267int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
268    if (sw >= 0 && sw <= SW_MAX) {
269        AutoMutex _l(mLock);
270
271        Device* device = getDeviceLocked(deviceId);
272        if (device != NULL) {
273            return getSwitchStateLocked(device, sw);
274        }
275    }
276    return AKEY_STATE_UNKNOWN;
277}
278
279int32_t EventHub::getSwitchStateLocked(Device* device, int32_t sw) const {
280    uint8_t sw_bitmask[sizeof_bit_array(SW_MAX + 1)];
281    memset(sw_bitmask, 0, sizeof(sw_bitmask));
282    if (ioctl(device->fd,
283               EVIOCGSW(sizeof(sw_bitmask)), sw_bitmask) >= 0) {
284        return test_bit(sw, sw_bitmask) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
285    }
286    return AKEY_STATE_UNKNOWN;
287}
288
289bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
290        const int32_t* keyCodes, uint8_t* outFlags) const {
291    AutoMutex _l(mLock);
292
293    Device* device = getDeviceLocked(deviceId);
294    if (device != NULL) {
295        return markSupportedKeyCodesLocked(device, numCodes, keyCodes, outFlags);
296    }
297    return false;
298}
299
300bool EventHub::markSupportedKeyCodesLocked(Device* device, size_t numCodes,
301        const int32_t* keyCodes, uint8_t* outFlags) const {
302    if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
303        return false;
304    }
305
306    Vector<int32_t> scanCodes;
307    for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
308        scanCodes.clear();
309
310        status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
311                keyCodes[codeIndex], &scanCodes);
312        if (! err) {
313            // check the possible scan codes identified by the layout map against the
314            // map of codes actually emitted by the driver
315            for (size_t sc = 0; sc < scanCodes.size(); sc++) {
316                if (test_bit(scanCodes[sc], device->keyBitmask)) {
317                    outFlags[codeIndex] = 1;
318                    break;
319                }
320            }
321        }
322    }
323    return true;
324}
325
326status_t EventHub::mapKey(int32_t deviceId, int scancode,
327        int32_t* outKeycode, uint32_t* outFlags) const
328{
329    AutoMutex _l(mLock);
330    Device* device = getDeviceLocked(deviceId);
331
332    if (device && device->keyMap.haveKeyLayout()) {
333        status_t err = device->keyMap.keyLayoutMap->mapKey(scancode, outKeycode, outFlags);
334        if (err == NO_ERROR) {
335            return NO_ERROR;
336        }
337    }
338
339    if (mBuiltInKeyboardId != -1) {
340        device = getDeviceLocked(mBuiltInKeyboardId);
341
342        if (device && device->keyMap.haveKeyLayout()) {
343            status_t err = device->keyMap.keyLayoutMap->mapKey(scancode, outKeycode, outFlags);
344            if (err == NO_ERROR) {
345                return NO_ERROR;
346            }
347        }
348    }
349
350    *outKeycode = 0;
351    *outFlags = 0;
352    return NAME_NOT_FOUND;
353}
354
355status_t EventHub::mapAxis(int32_t deviceId, int scancode, AxisInfo* outAxisInfo) const
356{
357    AutoMutex _l(mLock);
358    Device* device = getDeviceLocked(deviceId);
359
360    if (device && device->keyMap.haveKeyLayout()) {
361        status_t err = device->keyMap.keyLayoutMap->mapAxis(scancode, outAxisInfo);
362        if (err == NO_ERROR) {
363            return NO_ERROR;
364        }
365    }
366
367    if (mBuiltInKeyboardId != -1) {
368        device = getDeviceLocked(mBuiltInKeyboardId);
369
370        if (device && device->keyMap.haveKeyLayout()) {
371            status_t err = device->keyMap.keyLayoutMap->mapAxis(scancode, outAxisInfo);
372            if (err == NO_ERROR) {
373                return NO_ERROR;
374            }
375        }
376    }
377
378    return NAME_NOT_FOUND;
379}
380
381void EventHub::addExcludedDevice(const char* deviceName)
382{
383    AutoMutex _l(mLock);
384
385    String8 name(deviceName);
386    mExcludedDevices.push_back(name);
387}
388
389bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
390    AutoMutex _l(mLock);
391    Device* device = getDeviceLocked(deviceId);
392    if (device) {
393        uint8_t bitmask[sizeof_bit_array(LED_MAX + 1)];
394        memset(bitmask, 0, sizeof(bitmask));
395        if (ioctl(device->fd, EVIOCGBIT(EV_LED, sizeof(bitmask)), bitmask) >= 0) {
396            if (test_bit(led, bitmask)) {
397                return true;
398            }
399        }
400    }
401    return false;
402}
403
404void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
405    AutoMutex _l(mLock);
406    Device* device = getDeviceLocked(deviceId);
407    if (device) {
408        struct input_event ev;
409        ev.time.tv_sec = 0;
410        ev.time.tv_usec = 0;
411        ev.type = EV_LED;
412        ev.code = led;
413        ev.value = on ? 1 : 0;
414
415        ssize_t nWrite;
416        do {
417            nWrite = write(device->fd, &ev, sizeof(struct input_event));
418        } while (nWrite == -1 && errno == EINTR);
419    }
420}
421
422void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
423        Vector<VirtualKeyDefinition>& outVirtualKeys) const {
424    outVirtualKeys.clear();
425
426    AutoMutex _l(mLock);
427    Device* device = getDeviceLocked(deviceId);
428    if (device && device->virtualKeyMap) {
429        outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
430    }
431}
432
433EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
434    if (deviceId == 0) {
435        deviceId = mBuiltInKeyboardId;
436    }
437
438    size_t numDevices = mDevices.size();
439    for (size_t i = FIRST_ACTUAL_DEVICE_INDEX; i < numDevices; i++) {
440        Device* device = mDevices[i];
441        if (device->id == deviceId) {
442            return device;
443        }
444    }
445    return NULL;
446}
447
448bool EventHub::getEvent(int timeoutMillis, RawEvent* outEvent) {
449    outEvent->deviceId = 0;
450    outEvent->type = 0;
451    outEvent->scanCode = 0;
452    outEvent->keyCode = 0;
453    outEvent->flags = 0;
454    outEvent->value = 0;
455    outEvent->when = 0;
456
457    // Note that we only allow one caller to getEvent(), so don't need
458    // to do locking here...  only when adding/removing devices.
459
460    if (!mOpened) {
461        mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;
462        mOpened = true;
463        mNeedToSendFinishedDeviceScan = true;
464    }
465
466    for (;;) {
467        // Report any devices that had last been added/removed.
468        if (mClosingDevices != NULL) {
469            Device* device = mClosingDevices;
470            LOGV("Reporting device closed: id=%d, name=%s\n",
471                 device->id, device->path.string());
472            mClosingDevices = device->next;
473            if (device->id == mBuiltInKeyboardId) {
474                outEvent->deviceId = 0;
475            } else {
476                outEvent->deviceId = device->id;
477            }
478            outEvent->type = DEVICE_REMOVED;
479            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
480            delete device;
481            mNeedToSendFinishedDeviceScan = true;
482            return true;
483        }
484
485        if (mOpeningDevices != NULL) {
486            Device* device = mOpeningDevices;
487            LOGV("Reporting device opened: id=%d, name=%s\n",
488                 device->id, device->path.string());
489            mOpeningDevices = device->next;
490            if (device->id == mBuiltInKeyboardId) {
491                outEvent->deviceId = 0;
492            } else {
493                outEvent->deviceId = device->id;
494            }
495            outEvent->type = DEVICE_ADDED;
496            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
497            mNeedToSendFinishedDeviceScan = true;
498            return true;
499        }
500
501        if (mNeedToSendFinishedDeviceScan) {
502            mNeedToSendFinishedDeviceScan = false;
503            outEvent->type = FINISHED_DEVICE_SCAN;
504            outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
505            return true;
506        }
507
508        // Grab the next input event.
509        bool deviceWasRemoved = false;
510        for (;;) {
511            // Consume buffered input events, if any.
512            if (mInputBufferIndex < mInputBufferCount) {
513                const struct input_event& iev = mInputBufferData[mInputBufferIndex++];
514                const Device* device = mDevices[mInputFdIndex];
515
516                LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d", device->path.string(),
517                     (int) iev.time.tv_sec, (int) iev.time.tv_usec, iev.type, iev.code, iev.value);
518                if (device->id == mBuiltInKeyboardId) {
519                    outEvent->deviceId = 0;
520                } else {
521                    outEvent->deviceId = device->id;
522                }
523                outEvent->type = iev.type;
524                outEvent->scanCode = iev.code;
525                outEvent->flags = 0;
526                if (iev.type == EV_KEY) {
527                    outEvent->keyCode = AKEYCODE_UNKNOWN;
528                    if (device->keyMap.haveKeyLayout()) {
529                        status_t err = device->keyMap.keyLayoutMap->mapKey(iev.code,
530                                &outEvent->keyCode, &outEvent->flags);
531                        LOGV("iev.code=%d keyCode=%d flags=0x%08x err=%d\n",
532                                iev.code, outEvent->keyCode, outEvent->flags, err);
533                    }
534                } else {
535                    outEvent->keyCode = iev.code;
536                }
537                outEvent->value = iev.value;
538
539                // Use an event timestamp in the same timebase as
540                // java.lang.System.nanoTime() and android.os.SystemClock.uptimeMillis()
541                // as expected by the rest of the system.
542                outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);
543                return true;
544            }
545
546            // Finish reading all events from devices identified in previous poll().
547            // This code assumes that mInputDeviceIndex is initially 0 and that the
548            // revents member of pollfd is initialized to 0 when the device is first added.
549            // Since mFds[0] is used for inotify, we process regular events starting at index 1.
550            mInputFdIndex += 1;
551            if (mInputFdIndex >= mFds.size()) {
552                break;
553            }
554
555            const struct pollfd& pfd = mFds[mInputFdIndex];
556            if (pfd.revents & POLLIN) {
557                int32_t readSize = read(pfd.fd, mInputBufferData,
558                        sizeof(struct input_event) * INPUT_BUFFER_SIZE);
559                if (readSize < 0) {
560                    if (errno == ENODEV) {
561                        deviceWasRemoved = true;
562                        break;
563                    }
564                    if (errno != EAGAIN && errno != EINTR) {
565                        LOGW("could not get event (errno=%d)", errno);
566                    }
567                } else if ((readSize % sizeof(struct input_event)) != 0) {
568                    LOGE("could not get event (wrong size: %d)", readSize);
569                } else {
570                    mInputBufferCount = size_t(readSize) / sizeof(struct input_event);
571                    mInputBufferIndex = 0;
572                }
573            }
574        }
575
576        // Handle the case where a device has been removed but INotify has not yet noticed.
577        if (deviceWasRemoved) {
578            AutoMutex _l(mLock);
579            closeDeviceAtIndexLocked(mInputFdIndex);
580            continue; // report added or removed devices immediately
581        }
582
583#if HAVE_INOTIFY
584        // readNotify() will modify mFDs and mFDCount, so this must be done after
585        // processing all other events.
586        if(mFds[0].revents & POLLIN) {
587            readNotify(mFds[0].fd);
588            mFds.editItemAt(0).revents = 0;
589            continue; // report added or removed devices immediately
590        }
591#endif
592
593        // Poll for events.  Mind the wake lock dance!
594        // We hold a wake lock at all times except during poll().  This works due to some
595        // subtle choreography.  When a device driver has pending (unread) events, it acquires
596        // a kernel wake lock.  However, once the last pending event has been read, the device
597        // driver will release the kernel wake lock.  To prevent the system from going to sleep
598        // when this happens, the EventHub holds onto its own user wake lock while the client
599        // is processing events.  Thus the system can only sleep if there are no events
600        // pending or currently being processed.
601        //
602        // The timeout is advisory only.  If the device is asleep, it will not wake just to
603        // service the timeout.
604        release_wake_lock(WAKE_LOCK_ID);
605
606        int pollResult = poll(mFds.editArray(), mFds.size(), timeoutMillis);
607
608        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
609
610        if (pollResult == 0) {
611            // Timed out.
612            return false;
613        }
614        if (pollResult < 0) {
615            if (errno != EINTR) {
616                LOGW("poll failed (errno=%d)\n", errno);
617                usleep(100000);
618            }
619        }
620
621        // Prepare to process all of the FDs we just polled.
622        mInputFdIndex = 0;
623    }
624}
625
626/*
627 * Open the platform-specific input device.
628 */
629bool EventHub::openPlatformInput(void) {
630    /*
631     * Open platform-specific input device(s).
632     */
633    int res, fd;
634
635#ifdef HAVE_INOTIFY
636    fd = inotify_init();
637    res = inotify_add_watch(fd, DEVICE_PATH, IN_DELETE | IN_CREATE);
638    if(res < 0) {
639        LOGE("could not add watch for %s, %s\n", DEVICE_PATH, strerror(errno));
640    }
641#else
642    /*
643     * The code in EventHub::getEvent assumes that mFDs[0] is an inotify fd.
644     * We allocate space for it and set it to something invalid.
645     */
646    fd = -1;
647#endif
648
649    // Reserve fd index 0 for inotify.
650    struct pollfd pollfd;
651    pollfd.fd = fd;
652    pollfd.events = POLLIN;
653    pollfd.revents = 0;
654    mFds.push(pollfd);
655    mDevices.push(NULL);
656
657    res = scanDir(DEVICE_PATH);
658    if(res < 0) {
659        LOGE("scan dir failed for %s\n", DEVICE_PATH);
660    }
661
662    return true;
663}
664
665// ----------------------------------------------------------------------------
666
667static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
668    const uint8_t* end = array + endIndex;
669    array += startIndex;
670    while (array != end) {
671        if (*(array++) != 0) {
672            return true;
673        }
674    }
675    return false;
676}
677
678static const int32_t GAMEPAD_KEYCODES[] = {
679        AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
680        AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
681        AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
682        AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
683        AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
684        AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
685        AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
686        AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
687        AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
688        AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
689};
690
691int EventHub::openDevice(const char *devicePath) {
692    char buffer[80];
693
694    LOGV("Opening device: %s", devicePath);
695
696    AutoMutex _l(mLock);
697
698    int fd = open(devicePath, O_RDWR);
699    if(fd < 0) {
700        LOGE("could not open %s, %s\n", devicePath, strerror(errno));
701        return -1;
702    }
703
704    InputDeviceIdentifier identifier;
705
706    // Get device name.
707    if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
708        //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
709    } else {
710        buffer[sizeof(buffer) - 1] = '\0';
711        identifier.name.setTo(buffer);
712    }
713
714    // Check to see if the device is on our excluded list
715    List<String8>::iterator iter = mExcludedDevices.begin();
716    List<String8>::iterator end = mExcludedDevices.end();
717    for ( ; iter != end; iter++) {
718        const char* test = *iter;
719        if (identifier.name == test) {
720            LOGI("ignoring event id %s driver %s\n", devicePath, test);
721            close(fd);
722            return -1;
723        }
724    }
725
726    // Get device driver version.
727    int driverVersion;
728    if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
729        LOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
730        close(fd);
731        return -1;
732    }
733
734    // Get device identifier.
735    struct input_id inputId;
736    if(ioctl(fd, EVIOCGID, &inputId)) {
737        LOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
738        close(fd);
739        return -1;
740    }
741    identifier.bus = inputId.bustype;
742    identifier.product = inputId.product;
743    identifier.vendor = inputId.vendor;
744    identifier.version = inputId.version;
745
746    // Get device physical location.
747    if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
748        //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
749    } else {
750        buffer[sizeof(buffer) - 1] = '\0';
751        identifier.location.setTo(buffer);
752    }
753
754    // Get device unique id.
755    if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
756        //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
757    } else {
758        buffer[sizeof(buffer) - 1] = '\0';
759        identifier.uniqueId.setTo(buffer);
760    }
761
762    // Make file descriptor non-blocking for use with poll().
763    if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
764        LOGE("Error %d making device file descriptor non-blocking.", errno);
765        close(fd);
766        return -1;
767    }
768
769    // Allocate device.  (The device object takes ownership of the fd at this point.)
770    int32_t deviceId = mNextDeviceId++;
771    Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
772
773#if 0
774    LOGI("add device %d: %s\n", deviceId, devicePath);
775    LOGI("  bus:       %04x\n"
776         "  vendor     %04x\n"
777         "  product    %04x\n"
778         "  version    %04x\n",
779        identifier.bus, identifier.vendor, identifier.product, identifier.version);
780    LOGI("  name:      \"%s\"\n", identifier.name.string());
781    LOGI("  location:  \"%s\"\n", identifier.location.string());
782    LOGI("  unique id: \"%s\"\n", identifier.uniqueId.string());
783    LOGI("  driver:    v%d.%d.%d\n",
784        driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
785#endif
786
787    // Load the configuration file for the device.
788    loadConfiguration(device);
789
790    // Figure out the kinds of events the device reports.
791    uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];
792    memset(key_bitmask, 0, sizeof(key_bitmask));
793    ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask);
794
795    uint8_t abs_bitmask[sizeof_bit_array(ABS_MAX + 1)];
796    memset(abs_bitmask, 0, sizeof(abs_bitmask));
797    ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(abs_bitmask)), abs_bitmask);
798
799    uint8_t rel_bitmask[sizeof_bit_array(REL_MAX + 1)];
800    memset(rel_bitmask, 0, sizeof(rel_bitmask));
801    ioctl(fd, EVIOCGBIT(EV_REL, sizeof(rel_bitmask)), rel_bitmask);
802
803    uint8_t sw_bitmask[sizeof_bit_array(SW_MAX + 1)];
804    memset(sw_bitmask, 0, sizeof(sw_bitmask));
805    ioctl(fd, EVIOCGBIT(EV_SW, sizeof(sw_bitmask)), sw_bitmask);
806
807    device->keyBitmask = new uint8_t[sizeof(key_bitmask)];
808    if (device->keyBitmask != NULL) {
809        memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask));
810    } else {
811        delete device;
812        LOGE("out of memory allocating key bitmask");
813        return -1;
814    }
815
816    device->relBitmask = new uint8_t[sizeof(rel_bitmask)];
817    if (device->relBitmask != NULL) {
818        memcpy(device->relBitmask, rel_bitmask, sizeof(rel_bitmask));
819    } else {
820        delete device;
821        LOGE("out of memory allocating rel bitmask");
822        return -1;
823    }
824
825    // See if this is a keyboard.  Ignore everything in the button range except for
826    // joystick and gamepad buttons which are handled like keyboards for the most part.
827    bool haveKeyboardKeys = containsNonZeroByte(key_bitmask, 0, sizeof_bit_array(BTN_MISC))
828            || containsNonZeroByte(key_bitmask, sizeof_bit_array(KEY_OK),
829                    sizeof_bit_array(KEY_MAX + 1));
830    bool haveGamepadButtons = containsNonZeroByte(key_bitmask, sizeof_bit_array(BTN_MISC),
831                    sizeof_bit_array(BTN_MOUSE))
832            || containsNonZeroByte(key_bitmask, sizeof_bit_array(BTN_JOYSTICK),
833                    sizeof_bit_array(BTN_DIGI));
834    if (haveKeyboardKeys || haveGamepadButtons) {
835        device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
836    }
837
838    // See if this is a cursor device such as a trackball or mouse.
839    if (test_bit(BTN_MOUSE, key_bitmask)
840            && test_bit(REL_X, rel_bitmask)
841            && test_bit(REL_Y, rel_bitmask)) {
842        device->classes |= INPUT_DEVICE_CLASS_CURSOR;
843    }
844
845    // See if this is a touch pad.
846    // Is this a new modern multi-touch driver?
847    if (test_bit(ABS_MT_POSITION_X, abs_bitmask)
848            && test_bit(ABS_MT_POSITION_Y, abs_bitmask)) {
849        // Some joysticks such as the PS3 controller report axes that conflict
850        // with the ABS_MT range.  Try to confirm that the device really is
851        // a touch screen.
852        if (test_bit(BTN_TOUCH, key_bitmask) || !haveGamepadButtons) {
853            device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
854        }
855    // Is this an old style single-touch driver?
856    } else if (test_bit(BTN_TOUCH, key_bitmask)
857            && test_bit(ABS_X, abs_bitmask)
858            && test_bit(ABS_Y, abs_bitmask)) {
859        device->classes |= INPUT_DEVICE_CLASS_TOUCH;
860    }
861
862    // See if this device is a joystick.
863    // Ignore touchscreens because they use the same absolute axes for other purposes.
864    // Assumes that joysticks always have gamepad buttons in order to distinguish them
865    // from other devices such as accelerometers that also have absolute axes.
866    if (haveGamepadButtons
867            && !(device->classes & INPUT_DEVICE_CLASS_TOUCH)
868            && containsNonZeroByte(abs_bitmask, 0, sizeof_bit_array(ABS_MAX + 1))) {
869        device->classes |= INPUT_DEVICE_CLASS_JOYSTICK;
870    }
871
872    // figure out the switches this device reports
873    bool haveSwitches = false;
874    for (int i=0; i<EV_SW; i++) {
875        //LOGI("Device %d sw %d: has=%d", device->id, i, test_bit(i, sw_bitmask));
876        if (test_bit(i, sw_bitmask)) {
877            haveSwitches = true;
878            if (mSwitches[i] == 0) {
879                mSwitches[i] = device->id;
880            }
881        }
882    }
883    if (haveSwitches) {
884        device->classes |= INPUT_DEVICE_CLASS_SWITCH;
885    }
886
887    if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
888        // Load the virtual keys for the touch screen, if any.
889        // We do this now so that we can make sure to load the keymap if necessary.
890        status_t status = loadVirtualKeyMap(device);
891        if (!status) {
892            device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
893        }
894    }
895
896    // Load the key map.
897    // We need to do this for joysticks too because the key layout may specify axes.
898    status_t keyMapStatus = NAME_NOT_FOUND;
899    if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
900        // Load the keymap for the device.
901        keyMapStatus = loadKeyMap(device);
902    }
903
904    // Configure the keyboard, gamepad or virtual keyboard.
905    if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
906        // Set system properties for the keyboard.
907        setKeyboardProperties(device, false);
908
909        // Register the keyboard as a built-in keyboard if it is eligible.
910        if (!keyMapStatus
911                && mBuiltInKeyboardId == -1
912                && isEligibleBuiltInKeyboard(device->identifier,
913                        device->configuration, &device->keyMap)) {
914            mBuiltInKeyboardId = device->id;
915            setKeyboardProperties(device, true);
916        }
917
918        // 'Q' key support = cheap test of whether this is an alpha-capable kbd
919        if (hasKeycodeLocked(device, AKEYCODE_Q)) {
920            device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
921        }
922
923        // See if this device has a DPAD.
924        if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
925                hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
926                hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
927                hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
928                hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
929            device->classes |= INPUT_DEVICE_CLASS_DPAD;
930        }
931
932        // See if this device has a gamepad.
933        for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
934            if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
935                device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
936                break;
937            }
938        }
939    }
940
941    // If the device isn't recognized as something we handle, don't monitor it.
942    if (device->classes == 0) {
943        LOGV("Dropping device: id=%d, path='%s', name='%s'",
944                deviceId, devicePath, device->identifier.name.string());
945        delete device;
946        return -1;
947    }
948
949    // Determine whether the device is external or internal.
950    if (isExternalDevice(device)) {
951        device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
952    }
953
954    LOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
955            "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s",
956         deviceId, fd, devicePath, device->identifier.name.string(),
957         device->classes,
958         device->configurationFile.string(),
959         device->keyMap.keyLayoutFile.string(),
960         device->keyMap.keyCharacterMapFile.string(),
961         toString(mBuiltInKeyboardId == deviceId));
962
963    struct pollfd pollfd;
964    pollfd.fd = fd;
965    pollfd.events = POLLIN;
966    pollfd.revents = 0;
967    mFds.push(pollfd);
968    mDevices.push(device);
969
970    device->next = mOpeningDevices;
971    mOpeningDevices = device;
972    return 0;
973}
974
975void EventHub::loadConfiguration(Device* device) {
976    device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
977            device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
978    if (device->configurationFile.isEmpty()) {
979        LOGD("No input device configuration file found for device '%s'.",
980                device->identifier.name.string());
981    } else {
982        status_t status = PropertyMap::load(device->configurationFile,
983                &device->configuration);
984        if (status) {
985            LOGE("Error loading input device configuration file for device '%s'.  "
986                    "Using default configuration.",
987                    device->identifier.name.string());
988        }
989    }
990}
991
992status_t EventHub::loadVirtualKeyMap(Device* device) {
993    // The virtual key map is supplied by the kernel as a system board property file.
994    String8 path;
995    path.append("/sys/board_properties/virtualkeys.");
996    path.append(device->identifier.name);
997    if (access(path.string(), R_OK)) {
998        return NAME_NOT_FOUND;
999    }
1000    return VirtualKeyMap::load(path, &device->virtualKeyMap);
1001}
1002
1003status_t EventHub::loadKeyMap(Device* device) {
1004    return device->keyMap.load(device->identifier, device->configuration);
1005}
1006
1007void EventHub::setKeyboardProperties(Device* device, bool builtInKeyboard) {
1008    int32_t id = builtInKeyboard ? 0 : device->id;
1009    android::setKeyboardProperties(id, device->identifier,
1010            device->keyMap.keyLayoutFile, device->keyMap.keyCharacterMapFile);
1011}
1012
1013void EventHub::clearKeyboardProperties(Device* device, bool builtInKeyboard) {
1014    int32_t id = builtInKeyboard ? 0 : device->id;
1015    android::clearKeyboardProperties(id);
1016}
1017
1018bool EventHub::isExternalDevice(Device* device) {
1019    if (device->configuration) {
1020        bool value;
1021        if (device->configuration->tryGetProperty(String8("device.internal"), value)
1022                && value) {
1023            return false;
1024        }
1025    }
1026    return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1027}
1028
1029bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1030    if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
1031        return false;
1032    }
1033
1034    Vector<int32_t> scanCodes;
1035    device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1036    const size_t N = scanCodes.size();
1037    for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1038        int32_t sc = scanCodes.itemAt(i);
1039        if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1040            return true;
1041        }
1042    }
1043
1044    return false;
1045}
1046
1047int EventHub::closeDevice(const char *devicePath) {
1048    AutoMutex _l(mLock);
1049
1050    for (size_t i = FIRST_ACTUAL_DEVICE_INDEX; i < mDevices.size(); i++) {
1051        Device* device = mDevices[i];
1052        if (device->path == devicePath) {
1053            return closeDeviceAtIndexLocked(i);
1054        }
1055    }
1056    LOGV("Remove device: %s not found, device may already have been removed.", devicePath);
1057    return -1;
1058}
1059
1060int EventHub::closeDeviceAtIndexLocked(int index) {
1061    Device* device = mDevices[index];
1062    LOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
1063         device->path.string(), device->identifier.name.string(), device->id,
1064         device->fd, device->classes);
1065
1066    for (int j=0; j<EV_SW; j++) {
1067        if (mSwitches[j] == device->id) {
1068            mSwitches[j] = 0;
1069        }
1070    }
1071
1072    if (device->id == mBuiltInKeyboardId) {
1073        LOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
1074                device->path.string(), mBuiltInKeyboardId);
1075        mBuiltInKeyboardId = -1;
1076        clearKeyboardProperties(device, true);
1077    }
1078    clearKeyboardProperties(device, false);
1079
1080    mFds.removeAt(index);
1081    mDevices.removeAt(index);
1082    device->close();
1083
1084    // Unlink for opening devices list if it is present.
1085    Device* pred = NULL;
1086    bool found = false;
1087    for (Device* entry = mOpeningDevices; entry != NULL; ) {
1088        if (entry == device) {
1089            found = true;
1090            break;
1091        }
1092        pred = entry;
1093        entry = entry->next;
1094    }
1095    if (found) {
1096        // Unlink the device from the opening devices list then delete it.
1097        // We don't need to tell the client that the device was closed because
1098        // it does not even know it was opened in the first place.
1099        LOGI("Device %s was immediately closed after opening.", device->path.string());
1100        if (pred) {
1101            pred->next = device->next;
1102        } else {
1103            mOpeningDevices = device->next;
1104        }
1105        delete device;
1106    } else {
1107        // Link into closing devices list.
1108        // The device will be deleted later after we have informed the client.
1109        device->next = mClosingDevices;
1110        mClosingDevices = device;
1111    }
1112    return 0;
1113}
1114
1115int EventHub::readNotify(int nfd) {
1116#ifdef HAVE_INOTIFY
1117    int res;
1118    char devname[PATH_MAX];
1119    char *filename;
1120    char event_buf[512];
1121    int event_size;
1122    int event_pos = 0;
1123    struct inotify_event *event;
1124
1125    LOGV("EventHub::readNotify nfd: %d\n", nfd);
1126    res = read(nfd, event_buf, sizeof(event_buf));
1127    if(res < (int)sizeof(*event)) {
1128        if(errno == EINTR)
1129            return 0;
1130        LOGW("could not get event, %s\n", strerror(errno));
1131        return 1;
1132    }
1133    //printf("got %d bytes of event information\n", res);
1134
1135    strcpy(devname, DEVICE_PATH);
1136    filename = devname + strlen(devname);
1137    *filename++ = '/';
1138
1139    while(res >= (int)sizeof(*event)) {
1140        event = (struct inotify_event *)(event_buf + event_pos);
1141        //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1142        if(event->len) {
1143            strcpy(filename, event->name);
1144            if(event->mask & IN_CREATE) {
1145                openDevice(devname);
1146            }
1147            else {
1148                closeDevice(devname);
1149            }
1150        }
1151        event_size = sizeof(*event) + event->len;
1152        res -= event_size;
1153        event_pos += event_size;
1154    }
1155#endif
1156    return 0;
1157}
1158
1159int EventHub::scanDir(const char *dirname)
1160{
1161    char devname[PATH_MAX];
1162    char *filename;
1163    DIR *dir;
1164    struct dirent *de;
1165    dir = opendir(dirname);
1166    if(dir == NULL)
1167        return -1;
1168    strcpy(devname, dirname);
1169    filename = devname + strlen(devname);
1170    *filename++ = '/';
1171    while((de = readdir(dir))) {
1172        if(de->d_name[0] == '.' &&
1173           (de->d_name[1] == '\0' ||
1174            (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1175            continue;
1176        strcpy(filename, de->d_name);
1177        openDevice(devname);
1178    }
1179    closedir(dir);
1180    return 0;
1181}
1182
1183void EventHub::dump(String8& dump) {
1184    dump.append("Event Hub State:\n");
1185
1186    { // acquire lock
1187        AutoMutex _l(mLock);
1188
1189        dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
1190
1191        dump.append(INDENT "Devices:\n");
1192
1193        for (size_t i = FIRST_ACTUAL_DEVICE_INDEX; i < mDevices.size(); i++) {
1194            const Device* device = mDevices[i];
1195            if (device) {
1196                if (mBuiltInKeyboardId == device->id) {
1197                    dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1198                            device->id, device->identifier.name.string());
1199                } else {
1200                    dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1201                            device->identifier.name.string());
1202                }
1203                dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1204                dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
1205                dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1206                dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1207                dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1208                        "product=0x%04x, version=0x%04x\n",
1209                        device->identifier.bus, device->identifier.vendor,
1210                        device->identifier.product, device->identifier.version);
1211                dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1212                        device->keyMap.keyLayoutFile.string());
1213                dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1214                        device->keyMap.keyCharacterMapFile.string());
1215                dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1216                        device->configurationFile.string());
1217            }
1218        }
1219    } // release lock
1220}
1221
1222}; // namespace android
1223