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