michael@0: /* michael@0: * Copyright (C) 2005 The Android Open Source Project michael@0: * michael@0: * Licensed under the Apache License, Version 2.0 (the "License"); michael@0: * you may not use this file except in compliance with the License. michael@0: * You may obtain a copy of the License at michael@0: * michael@0: * http://www.apache.org/licenses/LICENSE-2.0 michael@0: * michael@0: * Unless required by applicable law or agreed to in writing, software michael@0: * distributed under the License is distributed on an "AS IS" BASIS, michael@0: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. michael@0: * See the License for the specific language governing permissions and michael@0: * limitations under the License. michael@0: */ michael@0: michael@0: #define LOG_TAG "EventHub" michael@0: michael@0: // #define LOG_NDEBUG 0 michael@0: #include "cutils_log.h" michael@0: michael@0: #include "EventHub.h" michael@0: michael@0: #include michael@0: michael@0: #include michael@0: #include "cutils_log.h" michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include "KeyLayoutMap.h" michael@0: #include "KeyCharacterMap.h" michael@0: #include "VirtualKeyMap.h" michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: #include michael@0: michael@0: /* this macro is used to tell if "bit" is set in "array" michael@0: * it selects a byte from the array, and does a boolean AND michael@0: * operation with a byte that only has the relevant bit set. michael@0: * eg. to check for the 12th bit, we do (array[1] & 1<<4) michael@0: */ michael@0: #define test_bit(bit, array) (array[bit/8] & (1<<(bit%8))) michael@0: michael@0: /* this macro computes the number of bytes needed to represent a bit array of the specified size */ michael@0: #define sizeof_bit_array(bits) ((bits + 7) / 8) michael@0: michael@0: #define INDENT " " michael@0: #define INDENT2 " " michael@0: #define INDENT3 " " michael@0: michael@0: namespace android { michael@0: michael@0: static const char *WAKE_LOCK_ID = "KeyEvents"; michael@0: static const char *DEVICE_PATH = "/dev/input"; michael@0: michael@0: /* return the larger integer */ michael@0: static inline int max(int v1, int v2) michael@0: { michael@0: return (v1 > v2) ? v1 : v2; michael@0: } michael@0: michael@0: static inline const char* toString(bool value) { michael@0: return value ? "true" : "false"; michael@0: } michael@0: michael@0: static String8 sha1(const String8& in) { michael@0: SHA1_CTX ctx; michael@0: SHA1Init(&ctx); michael@0: SHA1Update(&ctx, reinterpret_cast(in.string()), in.size()); michael@0: u_char digest[SHA1_DIGEST_LENGTH]; michael@0: SHA1Final(digest, &ctx); michael@0: michael@0: String8 out; michael@0: for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) { michael@0: out.appendFormat("%02x", digest[i]); michael@0: } michael@0: return out; michael@0: } michael@0: michael@0: static void setDescriptor(InputDeviceIdentifier& identifier) { michael@0: // Compute a device descriptor that uniquely identifies the device. michael@0: // The descriptor is assumed to be a stable identifier. Its value should not michael@0: // change between reboots, reconnections, firmware updates or new releases of Android. michael@0: // Ideally, we also want the descriptor to be short and relatively opaque. michael@0: String8 rawDescriptor; michael@0: rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product); michael@0: if (!identifier.uniqueId.isEmpty()) { michael@0: rawDescriptor.append("uniqueId:"); michael@0: rawDescriptor.append(identifier.uniqueId); michael@0: } if (identifier.vendor == 0 && identifier.product == 0) { michael@0: // If we don't know the vendor and product id, then the device is probably michael@0: // built-in so we need to rely on other information to uniquely identify michael@0: // the input device. Usually we try to avoid relying on the device name or michael@0: // location but for built-in input device, they are unlikely to ever change. michael@0: if (!identifier.name.isEmpty()) { michael@0: rawDescriptor.append("name:"); michael@0: rawDescriptor.append(identifier.name); michael@0: } else if (!identifier.location.isEmpty()) { michael@0: rawDescriptor.append("location:"); michael@0: rawDescriptor.append(identifier.location); michael@0: } michael@0: } michael@0: identifier.descriptor = sha1(rawDescriptor); michael@0: ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(), michael@0: identifier.descriptor.string()); michael@0: } michael@0: michael@0: // --- Global Functions --- michael@0: michael@0: uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) { michael@0: // Touch devices get dibs on touch-related axes. michael@0: if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) { michael@0: switch (axis) { michael@0: case ABS_X: michael@0: case ABS_Y: michael@0: case ABS_PRESSURE: michael@0: case ABS_TOOL_WIDTH: michael@0: case ABS_DISTANCE: michael@0: case ABS_TILT_X: michael@0: case ABS_TILT_Y: michael@0: case ABS_MT_SLOT: michael@0: case ABS_MT_TOUCH_MAJOR: michael@0: case ABS_MT_TOUCH_MINOR: michael@0: case ABS_MT_WIDTH_MAJOR: michael@0: case ABS_MT_WIDTH_MINOR: michael@0: case ABS_MT_ORIENTATION: michael@0: case ABS_MT_POSITION_X: michael@0: case ABS_MT_POSITION_Y: michael@0: case ABS_MT_TOOL_TYPE: michael@0: case ABS_MT_BLOB_ID: michael@0: case ABS_MT_TRACKING_ID: michael@0: case ABS_MT_PRESSURE: michael@0: case ABS_MT_DISTANCE: michael@0: return INPUT_DEVICE_CLASS_TOUCH; michael@0: } michael@0: } michael@0: michael@0: // Joystick devices get the rest. michael@0: return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK; michael@0: } michael@0: michael@0: // --- EventHub::Device --- michael@0: michael@0: EventHub::Device::Device(int fd, int32_t id, const String8& path, michael@0: const InputDeviceIdentifier& identifier) : michael@0: next(NULL), michael@0: fd(fd), id(id), path(path), identifier(identifier), michael@0: classes(0), configuration(NULL), virtualKeyMap(NULL), michael@0: ffEffectPlaying(false), ffEffectId(-1), michael@0: timestampOverrideSec(0), timestampOverrideUsec(0) { michael@0: memset(keyBitmask, 0, sizeof(keyBitmask)); michael@0: memset(absBitmask, 0, sizeof(absBitmask)); michael@0: memset(relBitmask, 0, sizeof(relBitmask)); michael@0: memset(swBitmask, 0, sizeof(swBitmask)); michael@0: memset(ledBitmask, 0, sizeof(ledBitmask)); michael@0: memset(ffBitmask, 0, sizeof(ffBitmask)); michael@0: memset(propBitmask, 0, sizeof(propBitmask)); michael@0: } michael@0: michael@0: EventHub::Device::~Device() { michael@0: close(); michael@0: delete configuration; michael@0: delete virtualKeyMap; michael@0: } michael@0: michael@0: void EventHub::Device::close() { michael@0: if (fd >= 0) { michael@0: ::close(fd); michael@0: fd = -1; michael@0: } michael@0: } michael@0: michael@0: michael@0: // --- EventHub --- michael@0: michael@0: const uint32_t EventHub::EPOLL_ID_INOTIFY; michael@0: const uint32_t EventHub::EPOLL_ID_WAKE; michael@0: const int EventHub::EPOLL_SIZE_HINT; michael@0: const int EventHub::EPOLL_MAX_EVENTS; michael@0: michael@0: EventHub::EventHub(void) : michael@0: mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), michael@0: mOpeningDevices(0), mClosingDevices(0), michael@0: mNeedToSendFinishedDeviceScan(false), michael@0: mNeedToReopenDevices(false), mNeedToScanDevices(true), michael@0: mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) { michael@0: acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID); michael@0: michael@0: mEpollFd = epoll_create(EPOLL_SIZE_HINT); michael@0: LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno); michael@0: michael@0: mINotifyFd = inotify_init(); michael@0: int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE); michael@0: LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d", michael@0: DEVICE_PATH, errno); michael@0: michael@0: struct epoll_event eventItem; michael@0: memset(&eventItem, 0, sizeof(eventItem)); michael@0: eventItem.events = EPOLLIN; michael@0: eventItem.data.u32 = EPOLL_ID_INOTIFY; michael@0: result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem); michael@0: LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno); michael@0: michael@0: int wakeFds[2]; michael@0: result = pipe(wakeFds); michael@0: LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno); michael@0: michael@0: mWakeReadPipeFd = wakeFds[0]; michael@0: mWakeWritePipeFd = wakeFds[1]; michael@0: michael@0: result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK); michael@0: LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d", michael@0: errno); michael@0: michael@0: result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK); michael@0: LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d", michael@0: errno); michael@0: michael@0: eventItem.data.u32 = EPOLL_ID_WAKE; michael@0: result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem); michael@0: LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d", michael@0: errno); michael@0: } michael@0: michael@0: EventHub::~EventHub(void) { michael@0: closeAllDevicesLocked(); michael@0: michael@0: while (mClosingDevices) { michael@0: Device* device = mClosingDevices; michael@0: mClosingDevices = device->next; michael@0: delete device; michael@0: } michael@0: michael@0: ::close(mEpollFd); michael@0: ::close(mINotifyFd); michael@0: ::close(mWakeReadPipeFd); michael@0: ::close(mWakeWritePipeFd); michael@0: michael@0: release_wake_lock(WAKE_LOCK_ID); michael@0: } michael@0: michael@0: InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device == NULL) return InputDeviceIdentifier(); michael@0: return device->identifier; michael@0: } michael@0: michael@0: uint32_t EventHub::getDeviceClasses(int32_t deviceId) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device == NULL) return 0; michael@0: return device->classes; michael@0: } michael@0: michael@0: void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && device->configuration) { michael@0: *outConfiguration = *device->configuration; michael@0: } else { michael@0: outConfiguration->clear(); michael@0: } michael@0: } michael@0: michael@0: status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis, michael@0: RawAbsoluteAxisInfo* outAxisInfo) const { michael@0: outAxisInfo->clear(); michael@0: michael@0: if (axis >= 0 && axis <= ABS_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) { michael@0: struct input_absinfo info; michael@0: if(ioctl(device->fd, EVIOCGABS(axis), &info)) { michael@0: ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", michael@0: axis, device->identifier.name.string(), device->fd, errno); michael@0: return -errno; michael@0: } michael@0: michael@0: if (info.minimum != info.maximum) { michael@0: outAxisInfo->valid = true; michael@0: outAxisInfo->minValue = info.minimum; michael@0: outAxisInfo->maxValue = info.maximum; michael@0: outAxisInfo->flat = info.flat; michael@0: outAxisInfo->fuzz = info.fuzz; michael@0: outAxisInfo->resolution = info.resolution; michael@0: } michael@0: return OK; michael@0: } michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const { michael@0: if (axis >= 0 && axis <= REL_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device) { michael@0: return test_bit(axis, device->relBitmask); michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: bool EventHub::hasInputProperty(int32_t deviceId, int property) const { michael@0: if (property >= 0 && property <= INPUT_PROP_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device) { michael@0: return test_bit(property, device->propBitmask); michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const { michael@0: if (scanCode >= 0 && scanCode <= KEY_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) { michael@0: uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)]; michael@0: memset(keyState, 0, sizeof(keyState)); michael@0: if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) { michael@0: return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP; michael@0: } michael@0: } michael@0: } michael@0: return AKEY_STATE_UNKNOWN; michael@0: } michael@0: michael@0: int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) { michael@0: Vector scanCodes; michael@0: device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes); michael@0: if (scanCodes.size() != 0) { michael@0: uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)]; michael@0: memset(keyState, 0, sizeof(keyState)); michael@0: if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) { michael@0: for (size_t i = 0; i < scanCodes.size(); i++) { michael@0: int32_t sc = scanCodes.itemAt(i); michael@0: if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) { michael@0: return AKEY_STATE_DOWN; michael@0: } michael@0: } michael@0: return AKEY_STATE_UP; michael@0: } michael@0: } michael@0: } michael@0: return AKEY_STATE_UNKNOWN; michael@0: } michael@0: michael@0: int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const { michael@0: if (sw >= 0 && sw <= SW_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) { michael@0: uint8_t swState[sizeof_bit_array(SW_MAX + 1)]; michael@0: memset(swState, 0, sizeof(swState)); michael@0: if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) { michael@0: return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP; michael@0: } michael@0: } michael@0: } michael@0: return AKEY_STATE_UNKNOWN; michael@0: } michael@0: michael@0: status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const { michael@0: *outValue = 0; michael@0: michael@0: if (axis >= 0 && axis <= ABS_MAX) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) { michael@0: struct input_absinfo info; michael@0: if(ioctl(device->fd, EVIOCGABS(axis), &info)) { michael@0: ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", michael@0: axis, device->identifier.name.string(), device->fd, errno); michael@0: return -errno; michael@0: } michael@0: michael@0: *outValue = info.value; michael@0: return OK; michael@0: } michael@0: } michael@0: return -1; michael@0: } michael@0: michael@0: bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, michael@0: const int32_t* keyCodes, uint8_t* outFlags) const { michael@0: AutoMutex _l(mLock); michael@0: michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && device->keyMap.haveKeyLayout()) { michael@0: Vector scanCodes; michael@0: for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) { michael@0: scanCodes.clear(); michael@0: michael@0: status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey( michael@0: keyCodes[codeIndex], &scanCodes); michael@0: if (! err) { michael@0: // check the possible scan codes identified by the layout map against the michael@0: // map of codes actually emitted by the driver michael@0: for (size_t sc = 0; sc < scanCodes.size(); sc++) { michael@0: if (test_bit(scanCodes[sc], device->keyBitmask)) { michael@0: outFlags[codeIndex] = 1; michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: return true; michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, michael@0: int32_t* outKeycode, uint32_t* outFlags) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: michael@0: if (device) { michael@0: // Check the key character map first. michael@0: sp kcm = device->getKeyCharacterMap(); michael@0: if (kcm != NULL) { michael@0: if (!kcm->mapKey(scanCode, usageCode, outKeycode)) { michael@0: *outFlags = 0; michael@0: return NO_ERROR; michael@0: } michael@0: } michael@0: michael@0: // Check the key layout next. michael@0: if (device->keyMap.haveKeyLayout()) { michael@0: if (!device->keyMap.keyLayoutMap->mapKey( michael@0: scanCode, usageCode, outKeycode, outFlags)) { michael@0: return NO_ERROR; michael@0: } michael@0: } michael@0: } michael@0: michael@0: *outKeycode = 0; michael@0: *outFlags = 0; michael@0: return NAME_NOT_FOUND; michael@0: } michael@0: michael@0: status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: michael@0: if (device && device->keyMap.haveKeyLayout()) { michael@0: status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo); michael@0: if (err == NO_ERROR) { michael@0: return NO_ERROR; michael@0: } michael@0: } michael@0: michael@0: return NAME_NOT_FOUND; michael@0: } michael@0: michael@0: void EventHub::setExcludedDevices(const Vector& devices) { michael@0: AutoMutex _l(mLock); michael@0: michael@0: mExcludedDevices = devices; michael@0: } michael@0: michael@0: bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && scanCode >= 0 && scanCode <= KEY_MAX) { michael@0: if (test_bit(scanCode, device->keyBitmask)) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: bool EventHub::hasLed(int32_t deviceId, int32_t led) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && led >= 0 && led <= LED_MAX) { michael@0: if (test_bit(led, device->ledBitmask)) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) { michael@0: struct input_event ev; michael@0: ev.time.tv_sec = 0; michael@0: ev.time.tv_usec = 0; michael@0: ev.type = EV_LED; michael@0: ev.code = led; michael@0: ev.value = on ? 1 : 0; michael@0: michael@0: ssize_t nWrite; michael@0: do { michael@0: nWrite = write(device->fd, &ev, sizeof(struct input_event)); michael@0: } while (nWrite == -1 && errno == EINTR); michael@0: } michael@0: } michael@0: michael@0: void EventHub::getVirtualKeyDefinitions(int32_t deviceId, michael@0: Vector& outVirtualKeys) const { michael@0: outVirtualKeys.clear(); michael@0: michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && device->virtualKeyMap) { michael@0: outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys()); michael@0: } michael@0: } michael@0: michael@0: sp EventHub::getKeyCharacterMap(int32_t deviceId) const { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device) { michael@0: return device->getKeyCharacterMap(); michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, michael@0: const sp& map) { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device) { michael@0: if (map != device->overlayKeyMap) { michael@0: device->overlayKeyMap = map; michael@0: device->combinedKeyMap = KeyCharacterMap::combine( michael@0: device->keyMap.keyCharacterMap, map); michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: void EventHub::vibrate(int32_t deviceId, nsecs_t duration) { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual()) { michael@0: ff_effect effect; michael@0: memset(&effect, 0, sizeof(effect)); michael@0: effect.type = FF_RUMBLE; michael@0: effect.id = device->ffEffectId; michael@0: effect.u.rumble.strong_magnitude = 0xc000; michael@0: effect.u.rumble.weak_magnitude = 0xc000; michael@0: effect.replay.length = (duration + 999999LL) / 1000000LL; michael@0: effect.replay.delay = 0; michael@0: if (ioctl(device->fd, EVIOCSFF, &effect)) { michael@0: ALOGW("Could not upload force feedback effect to device %s due to error %d.", michael@0: device->identifier.name.string(), errno); michael@0: return; michael@0: } michael@0: device->ffEffectId = effect.id; michael@0: michael@0: struct input_event ev; michael@0: ev.time.tv_sec = 0; michael@0: ev.time.tv_usec = 0; michael@0: ev.type = EV_FF; michael@0: ev.code = device->ffEffectId; michael@0: ev.value = 1; michael@0: if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { michael@0: ALOGW("Could not start force feedback effect on device %s due to error %d.", michael@0: device->identifier.name.string(), errno); michael@0: return; michael@0: } michael@0: device->ffEffectPlaying = true; michael@0: } michael@0: } michael@0: michael@0: void EventHub::cancelVibrate(int32_t deviceId) { michael@0: AutoMutex _l(mLock); michael@0: Device* device = getDeviceLocked(deviceId); michael@0: if (device && !device->isVirtual()) { michael@0: if (device->ffEffectPlaying) { michael@0: device->ffEffectPlaying = false; michael@0: michael@0: struct input_event ev; michael@0: ev.time.tv_sec = 0; michael@0: ev.time.tv_usec = 0; michael@0: ev.type = EV_FF; michael@0: ev.code = device->ffEffectId; michael@0: ev.value = 0; michael@0: if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) { michael@0: ALOGW("Could not stop force feedback effect on device %s due to error %d.", michael@0: device->identifier.name.string(), errno); michael@0: return; michael@0: } michael@0: } michael@0: } michael@0: } michael@0: michael@0: EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const { michael@0: if (deviceId == BUILT_IN_KEYBOARD_ID) { michael@0: deviceId = mBuiltInKeyboardId; michael@0: } michael@0: ssize_t index = mDevices.indexOfKey(deviceId); michael@0: return index >= 0 ? mDevices.valueAt(index) : NULL; michael@0: } michael@0: michael@0: EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const { michael@0: for (size_t i = 0; i < mDevices.size(); i++) { michael@0: Device* device = mDevices.valueAt(i); michael@0: if (device->path == devicePath) { michael@0: return device; michael@0: } michael@0: } michael@0: return NULL; michael@0: } michael@0: michael@0: size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) { michael@0: ALOG_ASSERT(bufferSize >= 1); michael@0: michael@0: AutoMutex _l(mLock); michael@0: michael@0: struct input_event readBuffer[bufferSize]; michael@0: michael@0: RawEvent* event = buffer; michael@0: size_t capacity = bufferSize; michael@0: bool awoken = false; michael@0: for (;;) { michael@0: nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); michael@0: michael@0: // Reopen input devices if needed. michael@0: if (mNeedToReopenDevices) { michael@0: mNeedToReopenDevices = false; michael@0: michael@0: ALOGI("Reopening all input devices due to a configuration change."); michael@0: michael@0: closeAllDevicesLocked(); michael@0: mNeedToScanDevices = true; michael@0: break; // return to the caller before we actually rescan michael@0: } michael@0: michael@0: // Report any devices that had last been added/removed. michael@0: while (mClosingDevices) { michael@0: Device* device = mClosingDevices; michael@0: ALOGV("Reporting device closed: id=%d, name=%s\n", michael@0: device->id, device->path.string()); michael@0: mClosingDevices = device->next; michael@0: event->when = now; michael@0: event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id; michael@0: event->type = DEVICE_REMOVED; michael@0: event += 1; michael@0: delete device; michael@0: mNeedToSendFinishedDeviceScan = true; michael@0: if (--capacity == 0) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (mNeedToScanDevices) { michael@0: mNeedToScanDevices = false; michael@0: scanDevicesLocked(); michael@0: mNeedToSendFinishedDeviceScan = true; michael@0: } michael@0: michael@0: while (mOpeningDevices != NULL) { michael@0: Device* device = mOpeningDevices; michael@0: ALOGV("Reporting device opened: id=%d, name=%s\n", michael@0: device->id, device->path.string()); michael@0: mOpeningDevices = device->next; michael@0: event->when = now; michael@0: event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id; michael@0: event->type = DEVICE_ADDED; michael@0: event += 1; michael@0: mNeedToSendFinishedDeviceScan = true; michael@0: if (--capacity == 0) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: if (mNeedToSendFinishedDeviceScan) { michael@0: mNeedToSendFinishedDeviceScan = false; michael@0: event->when = now; michael@0: event->type = FINISHED_DEVICE_SCAN; michael@0: event += 1; michael@0: if (--capacity == 0) { michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // Grab the next input event. michael@0: bool deviceChanged = false; michael@0: while (mPendingEventIndex < mPendingEventCount) { michael@0: const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++]; michael@0: if (eventItem.data.u32 == EPOLL_ID_INOTIFY) { michael@0: if (eventItem.events & EPOLLIN) { michael@0: mPendingINotify = true; michael@0: } else { michael@0: ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events); michael@0: } michael@0: continue; michael@0: } michael@0: michael@0: if (eventItem.data.u32 == EPOLL_ID_WAKE) { michael@0: if (eventItem.events & EPOLLIN) { michael@0: ALOGV("awoken after wake()"); michael@0: awoken = true; michael@0: char buffer[16]; michael@0: ssize_t nRead; michael@0: do { michael@0: nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer)); michael@0: } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer)); michael@0: } else { michael@0: ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.", michael@0: eventItem.events); michael@0: } michael@0: continue; michael@0: } michael@0: michael@0: ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32); michael@0: if (deviceIndex < 0) { michael@0: ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.", michael@0: eventItem.events, eventItem.data.u32); michael@0: continue; michael@0: } michael@0: michael@0: Device* device = mDevices.valueAt(deviceIndex); michael@0: if (eventItem.events & EPOLLIN) { michael@0: int32_t readSize = read(device->fd, readBuffer, michael@0: sizeof(struct input_event) * capacity); michael@0: if (readSize == 0 || (readSize < 0 && errno == ENODEV)) { michael@0: // Device was removed before INotify noticed. michael@0: ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d " michael@0: "capacity: %d errno: %d)\n", michael@0: device->fd, readSize, bufferSize, capacity, errno); michael@0: deviceChanged = true; michael@0: closeDeviceLocked(device); michael@0: } else if (readSize < 0) { michael@0: if (errno != EAGAIN && errno != EINTR) { michael@0: ALOGW("could not get event (errno=%d)", errno); michael@0: } michael@0: } else if ((readSize % sizeof(struct input_event)) != 0) { michael@0: ALOGE("could not get event (wrong size: %d)", readSize); michael@0: } else { michael@0: int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id; michael@0: michael@0: size_t count = size_t(readSize) / sizeof(struct input_event); michael@0: for (size_t i = 0; i < count; i++) { michael@0: struct input_event& iev = readBuffer[i]; michael@0: ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d", michael@0: device->path.string(), michael@0: (int) iev.time.tv_sec, (int) iev.time.tv_usec, michael@0: iev.type, iev.code, iev.value); michael@0: michael@0: // Some input devices may have a better concept of the time michael@0: // when an input event was actually generated than the kernel michael@0: // which simply timestamps all events on entry to evdev. michael@0: // This is a custom Android extension of the input protocol michael@0: // mainly intended for use with uinput based device drivers. michael@0: if (iev.type == EV_MSC) { michael@0: if (iev.code == MSC_ANDROID_TIME_SEC) { michael@0: device->timestampOverrideSec = iev.value; michael@0: continue; michael@0: } else if (iev.code == MSC_ANDROID_TIME_USEC) { michael@0: device->timestampOverrideUsec = iev.value; michael@0: continue; michael@0: } michael@0: } michael@0: if (device->timestampOverrideSec || device->timestampOverrideUsec) { michael@0: iev.time.tv_sec = device->timestampOverrideSec; michael@0: iev.time.tv_usec = device->timestampOverrideUsec; michael@0: if (iev.type == EV_SYN && iev.code == SYN_REPORT) { michael@0: device->timestampOverrideSec = 0; michael@0: device->timestampOverrideUsec = 0; michael@0: } michael@0: ALOGV("applied override time %d.%06d", michael@0: int(iev.time.tv_sec), int(iev.time.tv_usec)); michael@0: } michael@0: michael@0: #ifdef HAVE_POSIX_CLOCKS michael@0: // Use the time specified in the event instead of the current time michael@0: // so that downstream code can get more accurate estimates of michael@0: // event dispatch latency from the time the event is enqueued onto michael@0: // the evdev client buffer. michael@0: // michael@0: // The event's timestamp fortuitously uses the same monotonic clock michael@0: // time base as the rest of Android. The kernel event device driver michael@0: // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts(). michael@0: // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere michael@0: // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a michael@0: // system call that also queries ktime_get_ts(). michael@0: event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL michael@0: + nsecs_t(iev.time.tv_usec) * 1000LL; michael@0: ALOGV("event time %lld, now %lld", event->when, now); michael@0: michael@0: // Bug 7291243: Add a guard in case the kernel generates timestamps michael@0: // that appear to be far into the future because they were generated michael@0: // using the wrong clock source. michael@0: // michael@0: // This can happen because when the input device is initially opened michael@0: // it has a default clock source of CLOCK_REALTIME. Any input events michael@0: // enqueued right after the device is opened will have timestamps michael@0: // generated using CLOCK_REALTIME. We later set the clock source michael@0: // to CLOCK_MONOTONIC but it is already too late. michael@0: // michael@0: // Invalid input event timestamps can result in ANRs, crashes and michael@0: // and other issues that are hard to track down. We must not let them michael@0: // propagate through the system. michael@0: // michael@0: // Log a warning so that we notice the problem and recover gracefully. michael@0: if (event->when >= now + 10 * 1000000000LL) { michael@0: // Double-check. Time may have moved on. michael@0: nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC); michael@0: if (event->when > time) { michael@0: ALOGW("An input event from %s has a timestamp that appears to " michael@0: "have been generated using the wrong clock source " michael@0: "(expected CLOCK_MONOTONIC): " michael@0: "event time %lld, current time %lld, call time %lld. " michael@0: "Using current time instead.", michael@0: device->path.string(), event->when, time, now); michael@0: event->when = time; michael@0: } else { michael@0: ALOGV("Event time is ok but failed the fast path and required " michael@0: "an extra call to systemTime: " michael@0: "event time %lld, current time %lld, call time %lld.", michael@0: event->when, time, now); michael@0: } michael@0: } michael@0: #else michael@0: event->when = now; michael@0: #endif michael@0: event->deviceId = deviceId; michael@0: event->type = iev.type; michael@0: event->code = iev.code; michael@0: event->value = iev.value; michael@0: event += 1; michael@0: capacity -= 1; michael@0: } michael@0: if (capacity == 0) { michael@0: // The result buffer is full. Reset the pending event index michael@0: // so we will try to read the device again on the next iteration. michael@0: mPendingEventIndex -= 1; michael@0: break; michael@0: } michael@0: } michael@0: } else if (eventItem.events & EPOLLHUP) { michael@0: ALOGI("Removing device %s due to epoll hang-up event.", michael@0: device->identifier.name.string()); michael@0: deviceChanged = true; michael@0: closeDeviceLocked(device); michael@0: } else { michael@0: ALOGW("Received unexpected epoll event 0x%08x for device %s.", michael@0: eventItem.events, device->identifier.name.string()); michael@0: } michael@0: } michael@0: michael@0: // readNotify() will modify the list of devices so this must be done after michael@0: // processing all other events to ensure that we read all remaining events michael@0: // before closing the devices. michael@0: if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) { michael@0: mPendingINotify = false; michael@0: readNotifyLocked(); michael@0: deviceChanged = true; michael@0: } michael@0: michael@0: // Report added or removed devices immediately. michael@0: if (deviceChanged) { michael@0: continue; michael@0: } michael@0: michael@0: // Return now if we have collected any events or if we were explicitly awoken. michael@0: if (event != buffer || awoken) { michael@0: break; michael@0: } michael@0: michael@0: // Poll for events. Mind the wake lock dance! michael@0: // We hold a wake lock at all times except during epoll_wait(). This works due to some michael@0: // subtle choreography. When a device driver has pending (unread) events, it acquires michael@0: // a kernel wake lock. However, once the last pending event has been read, the device michael@0: // driver will release the kernel wake lock. To prevent the system from going to sleep michael@0: // when this happens, the EventHub holds onto its own user wake lock while the client michael@0: // is processing events. Thus the system can only sleep if there are no events michael@0: // pending or currently being processed. michael@0: // michael@0: // The timeout is advisory only. If the device is asleep, it will not wake just to michael@0: // service the timeout. michael@0: mPendingEventIndex = 0; michael@0: michael@0: mLock.unlock(); // release lock before poll, must be before release_wake_lock michael@0: release_wake_lock(WAKE_LOCK_ID); michael@0: michael@0: int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis); michael@0: michael@0: acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID); michael@0: mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock michael@0: michael@0: if (pollResult == 0) { michael@0: // Timed out. michael@0: mPendingEventCount = 0; michael@0: break; michael@0: } michael@0: michael@0: if (pollResult < 0) { michael@0: // An error occurred. michael@0: mPendingEventCount = 0; michael@0: michael@0: // Sleep after errors to avoid locking up the system. michael@0: // Hopefully the error is transient. michael@0: if (errno != EINTR) { michael@0: ALOGW("poll failed (errno=%d)\n", errno); michael@0: usleep(100000); michael@0: } michael@0: } else { michael@0: // Some events occurred. michael@0: mPendingEventCount = size_t(pollResult); michael@0: } michael@0: } michael@0: michael@0: // All done, return the number of events we read. michael@0: return event - buffer; michael@0: } michael@0: michael@0: void EventHub::wake() { michael@0: ALOGV("wake() called"); michael@0: michael@0: ssize_t nWrite; michael@0: do { michael@0: nWrite = write(mWakeWritePipeFd, "W", 1); michael@0: } while (nWrite == -1 && errno == EINTR); michael@0: michael@0: if (nWrite != 1 && errno != EAGAIN) { michael@0: ALOGW("Could not write wake signal, errno=%d", errno); michael@0: } michael@0: } michael@0: michael@0: void EventHub::scanDevicesLocked() { michael@0: status_t res = scanDirLocked(DEVICE_PATH); michael@0: if(res < 0) { michael@0: ALOGE("scan dir failed for %s\n", DEVICE_PATH); michael@0: } michael@0: if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) { michael@0: createVirtualKeyboardLocked(); michael@0: } michael@0: } michael@0: michael@0: // ---------------------------------------------------------------------------- michael@0: michael@0: static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) { michael@0: const uint8_t* end = array + endIndex; michael@0: array += startIndex; michael@0: while (array != end) { michael@0: if (*(array++) != 0) { michael@0: return true; michael@0: } michael@0: } michael@0: return false; michael@0: } michael@0: michael@0: static const int32_t GAMEPAD_KEYCODES[] = { michael@0: AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, michael@0: AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, michael@0: AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, michael@0: AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, michael@0: AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, michael@0: AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, michael@0: AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4, michael@0: AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8, michael@0: AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12, michael@0: AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16, michael@0: }; michael@0: michael@0: status_t EventHub::openDeviceLocked(const char *devicePath) { michael@0: char buffer[80]; michael@0: michael@0: ALOGV("Opening device: %s", devicePath); michael@0: michael@0: int fd = open(devicePath, O_RDWR | O_CLOEXEC); michael@0: if(fd < 0) { michael@0: ALOGE("could not open %s, %s\n", devicePath, strerror(errno)); michael@0: return -1; michael@0: } michael@0: michael@0: InputDeviceIdentifier identifier; michael@0: michael@0: // Get device name. michael@0: if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) { michael@0: //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno)); michael@0: } else { michael@0: buffer[sizeof(buffer) - 1] = '\0'; michael@0: identifier.name.setTo(buffer); michael@0: } michael@0: michael@0: // Check to see if the device is on our excluded list michael@0: for (size_t i = 0; i < mExcludedDevices.size(); i++) { michael@0: const String8& item = mExcludedDevices.itemAt(i); michael@0: if (identifier.name == item) { michael@0: ALOGI("ignoring event id %s driver %s\n", devicePath, item.string()); michael@0: close(fd); michael@0: return -1; michael@0: } michael@0: } michael@0: michael@0: // Get device driver version. michael@0: int driverVersion; michael@0: if(ioctl(fd, EVIOCGVERSION, &driverVersion)) { michael@0: ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno)); michael@0: close(fd); michael@0: return -1; michael@0: } michael@0: michael@0: // Get device identifier. michael@0: struct input_id inputId; michael@0: if(ioctl(fd, EVIOCGID, &inputId)) { michael@0: ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno)); michael@0: close(fd); michael@0: return -1; michael@0: } michael@0: identifier.bus = inputId.bustype; michael@0: identifier.product = inputId.product; michael@0: identifier.vendor = inputId.vendor; michael@0: identifier.version = inputId.version; michael@0: michael@0: // Get device physical location. michael@0: if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) { michael@0: //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno)); michael@0: } else { michael@0: buffer[sizeof(buffer) - 1] = '\0'; michael@0: identifier.location.setTo(buffer); michael@0: } michael@0: michael@0: // Get device unique id. michael@0: if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) { michael@0: //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno)); michael@0: } else { michael@0: buffer[sizeof(buffer) - 1] = '\0'; michael@0: identifier.uniqueId.setTo(buffer); michael@0: } michael@0: michael@0: // Fill in the descriptor. michael@0: setDescriptor(identifier); michael@0: michael@0: // Make file descriptor non-blocking for use with poll(). michael@0: if (fcntl(fd, F_SETFL, O_NONBLOCK)) { michael@0: ALOGE("Error %d making device file descriptor non-blocking.", errno); michael@0: close(fd); michael@0: return -1; michael@0: } michael@0: michael@0: // Allocate device. (The device object takes ownership of the fd at this point.) michael@0: int32_t deviceId = mNextDeviceId++; michael@0: Device* device = new Device(fd, deviceId, String8(devicePath), identifier); michael@0: michael@0: ALOGV("add device %d: %s\n", deviceId, devicePath); michael@0: ALOGV(" bus: %04x\n" michael@0: " vendor %04x\n" michael@0: " product %04x\n" michael@0: " version %04x\n", michael@0: identifier.bus, identifier.vendor, identifier.product, identifier.version); michael@0: ALOGV(" name: \"%s\"\n", identifier.name.string()); michael@0: ALOGV(" location: \"%s\"\n", identifier.location.string()); michael@0: ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string()); michael@0: ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string()); michael@0: ALOGV(" driver: v%d.%d.%d\n", michael@0: driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff); michael@0: michael@0: // Load the configuration file for the device. michael@0: loadConfigurationLocked(device); michael@0: michael@0: // Figure out the kinds of events the device reports. michael@0: ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask); michael@0: ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask); michael@0: ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask); michael@0: ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask); michael@0: ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask); michael@0: ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask); michael@0: ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask); michael@0: michael@0: // See if this is a keyboard. Ignore everything in the button range except for michael@0: // joystick and gamepad buttons which are handled like keyboards for the most part. michael@0: bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC)) michael@0: || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK), michael@0: sizeof_bit_array(KEY_MAX + 1)); michael@0: bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC), michael@0: sizeof_bit_array(BTN_MOUSE)) michael@0: || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK), michael@0: sizeof_bit_array(BTN_DIGI)); michael@0: if (haveKeyboardKeys || haveGamepadButtons) { michael@0: device->classes |= INPUT_DEVICE_CLASS_KEYBOARD; michael@0: } michael@0: michael@0: // See if this is a cursor device such as a trackball or mouse. michael@0: if (test_bit(BTN_MOUSE, device->keyBitmask) michael@0: && test_bit(REL_X, device->relBitmask) michael@0: && test_bit(REL_Y, device->relBitmask)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_CURSOR; michael@0: } michael@0: michael@0: // See if this is a touch pad. michael@0: // Is this a new modern multi-touch driver? michael@0: if (test_bit(ABS_MT_POSITION_X, device->absBitmask) michael@0: && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) { michael@0: // Some joysticks such as the PS3 controller report axes that conflict michael@0: // with the ABS_MT range. Try to confirm that the device really is michael@0: // a touch screen. michael@0: if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) { michael@0: device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT; michael@0: } michael@0: // Is this an old style single-touch driver? michael@0: } else if (test_bit(BTN_TOUCH, device->keyBitmask) michael@0: && test_bit(ABS_X, device->absBitmask) michael@0: && test_bit(ABS_Y, device->absBitmask)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_TOUCH; michael@0: } michael@0: michael@0: // See if this device is a joystick. michael@0: // Assumes that joysticks always have gamepad buttons in order to distinguish them michael@0: // from other devices such as accelerometers that also have absolute axes. michael@0: if (haveGamepadButtons) { michael@0: uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK; michael@0: for (int i = 0; i <= ABS_MAX; i++) { michael@0: if (test_bit(i, device->absBitmask) michael@0: && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) { michael@0: device->classes = assumedClasses; michael@0: break; michael@0: } michael@0: } michael@0: } michael@0: michael@0: // Check whether this device has switches. michael@0: for (int i = 0; i <= SW_MAX; i++) { michael@0: if (test_bit(i, device->swBitmask)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_SWITCH; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // Check whether this device supports the vibrator. michael@0: if (test_bit(FF_RUMBLE, device->ffBitmask)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_VIBRATOR; michael@0: } michael@0: michael@0: // Configure virtual keys. michael@0: if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) { michael@0: // Load the virtual keys for the touch screen, if any. michael@0: // We do this now so that we can make sure to load the keymap if necessary. michael@0: status_t status = loadVirtualKeyMapLocked(device); michael@0: if (!status) { michael@0: device->classes |= INPUT_DEVICE_CLASS_KEYBOARD; michael@0: } michael@0: } michael@0: michael@0: // Load the key map. michael@0: // We need to do this for joysticks too because the key layout may specify axes. michael@0: status_t keyMapStatus = NAME_NOT_FOUND; michael@0: if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) { michael@0: // Load the keymap for the device. michael@0: keyMapStatus = loadKeyMapLocked(device); michael@0: } michael@0: michael@0: // Configure the keyboard, gamepad or virtual keyboard. michael@0: if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) { michael@0: // Register the keyboard as a built-in keyboard if it is eligible. michael@0: if (!keyMapStatus michael@0: && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD michael@0: && isEligibleBuiltInKeyboard(device->identifier, michael@0: device->configuration, &device->keyMap)) { michael@0: mBuiltInKeyboardId = device->id; michael@0: } michael@0: michael@0: // 'Q' key support = cheap test of whether this is an alpha-capable kbd michael@0: if (hasKeycodeLocked(device, AKEYCODE_Q)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY; michael@0: } michael@0: michael@0: // See if this device has a DPAD. michael@0: if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) && michael@0: hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) && michael@0: hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) && michael@0: hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) && michael@0: hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_DPAD; michael@0: } michael@0: michael@0: // See if this device has a gamepad. michael@0: for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) { michael@0: if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) { michael@0: device->classes |= INPUT_DEVICE_CLASS_GAMEPAD; michael@0: break; michael@0: } michael@0: } michael@0: michael@0: // Disable kernel key repeat since we handle it ourselves michael@0: unsigned int repeatRate[] = {0,0}; michael@0: if (ioctl(fd, EVIOCSREP, repeatRate)) { michael@0: ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno)); michael@0: } michael@0: } michael@0: michael@0: // If the device isn't recognized as something we handle, don't monitor it. michael@0: if (device->classes == 0) { michael@0: ALOGV("Dropping device: id=%d, path='%s', name='%s'", michael@0: deviceId, devicePath, device->identifier.name.string()); michael@0: delete device; michael@0: return -1; michael@0: } michael@0: michael@0: // Determine whether the device is external or internal. michael@0: if (isExternalDeviceLocked(device)) { michael@0: device->classes |= INPUT_DEVICE_CLASS_EXTERNAL; michael@0: } michael@0: michael@0: // Register with epoll. michael@0: struct epoll_event eventItem; michael@0: memset(&eventItem, 0, sizeof(eventItem)); michael@0: eventItem.events = EPOLLIN; michael@0: eventItem.data.u32 = deviceId; michael@0: if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) { michael@0: ALOGE("Could not add device fd to epoll instance. errno=%d", errno); michael@0: delete device; michael@0: return -1; michael@0: } michael@0: michael@0: // Enable wake-lock behavior on kernels that support it. michael@0: // TODO: Only need this for devices that can really wake the system. michael@0: bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1); michael@0: michael@0: // Tell the kernel that we want to use the monotonic clock for reporting timestamps michael@0: // associated with input events. This is important because the input system michael@0: // uses the timestamps extensively and assumes they were recorded using the monotonic michael@0: // clock. michael@0: // michael@0: // In older kernel, before Linux 3.4, there was no way to tell the kernel which michael@0: // clock to use to input event timestamps. The standard kernel behavior was to michael@0: // record a real time timestamp, which isn't what we want. Android kernels therefore michael@0: // contained a patch to the evdev_event() function in drivers/input/evdev.c to michael@0: // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic michael@0: // clock to be used instead of the real time clock. michael@0: // michael@0: // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock. michael@0: // Therefore, we no longer require the Android-specific kernel patch described above michael@0: // as long as we make sure to set select the monotonic clock. We do that here. michael@0: int clockId = CLOCK_MONOTONIC; michael@0: bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId); michael@0: michael@0: ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, " michael@0: "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, " michael@0: "usingSuspendBlockIoctl=%s, usingClockIoctl=%s", michael@0: deviceId, fd, devicePath, device->identifier.name.string(), michael@0: device->classes, michael@0: device->configurationFile.string(), michael@0: device->keyMap.keyLayoutFile.string(), michael@0: device->keyMap.keyCharacterMapFile.string(), michael@0: toString(mBuiltInKeyboardId == deviceId), michael@0: toString(usingSuspendBlockIoctl), toString(usingClockIoctl)); michael@0: michael@0: addDeviceLocked(device); michael@0: return 0; michael@0: } michael@0: michael@0: void EventHub::createVirtualKeyboardLocked() { michael@0: InputDeviceIdentifier identifier; michael@0: identifier.name = "Virtual"; michael@0: identifier.uniqueId = ""; michael@0: setDescriptor(identifier); michael@0: michael@0: Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8(""), identifier); michael@0: device->classes = INPUT_DEVICE_CLASS_KEYBOARD michael@0: | INPUT_DEVICE_CLASS_ALPHAKEY michael@0: | INPUT_DEVICE_CLASS_DPAD michael@0: | INPUT_DEVICE_CLASS_VIRTUAL; michael@0: loadKeyMapLocked(device); michael@0: addDeviceLocked(device); michael@0: } michael@0: michael@0: void EventHub::addDeviceLocked(Device* device) { michael@0: mDevices.add(device->id, device); michael@0: device->next = mOpeningDevices; michael@0: mOpeningDevices = device; michael@0: } michael@0: michael@0: void EventHub::loadConfigurationLocked(Device* device) { michael@0: device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier( michael@0: device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION); michael@0: if (device->configurationFile.isEmpty()) { michael@0: ALOGD("No input device configuration file found for device '%s'.", michael@0: device->identifier.name.string()); michael@0: } else { michael@0: status_t status = PropertyMap::load(device->configurationFile, michael@0: &device->configuration); michael@0: if (status) { michael@0: ALOGE("Error loading input device configuration file for device '%s'. " michael@0: "Using default configuration.", michael@0: device->identifier.name.string()); michael@0: } michael@0: } michael@0: } michael@0: michael@0: status_t EventHub::loadVirtualKeyMapLocked(Device* device) { michael@0: // The virtual key map is supplied by the kernel as a system board property file. michael@0: String8 path; michael@0: path.append("/sys/board_properties/virtualkeys."); michael@0: path.append(device->identifier.name); michael@0: if (access(path.string(), R_OK)) { michael@0: return NAME_NOT_FOUND; michael@0: } michael@0: return VirtualKeyMap::load(path, &device->virtualKeyMap); michael@0: } michael@0: michael@0: status_t EventHub::loadKeyMapLocked(Device* device) { michael@0: return device->keyMap.load(device->identifier, device->configuration); michael@0: } michael@0: michael@0: bool EventHub::isExternalDeviceLocked(Device* device) { michael@0: if (device->configuration) { michael@0: bool value; michael@0: if (device->configuration->tryGetProperty(String8("device.internal"), value)) { michael@0: return !value; michael@0: } michael@0: } michael@0: return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH; michael@0: } michael@0: michael@0: bool EventHub::hasKeycodeLocked(Device* device, int keycode) const { michael@0: if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) { michael@0: return false; michael@0: } michael@0: michael@0: Vector scanCodes; michael@0: device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes); michael@0: const size_t N = scanCodes.size(); michael@0: for (size_t i=0; i= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) { michael@0: return true; michael@0: } michael@0: } michael@0: michael@0: return false; michael@0: } michael@0: michael@0: status_t EventHub::closeDeviceByPathLocked(const char *devicePath) { michael@0: Device* device = getDeviceByPathLocked(devicePath); michael@0: if (device) { michael@0: closeDeviceLocked(device); michael@0: return 0; michael@0: } michael@0: ALOGV("Remove device: %s not found, device may already have been removed.", devicePath); michael@0: return -1; michael@0: } michael@0: michael@0: void EventHub::closeAllDevicesLocked() { michael@0: while (mDevices.size() > 0) { michael@0: closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1)); michael@0: } michael@0: } michael@0: michael@0: void EventHub::closeDeviceLocked(Device* device) { michael@0: ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n", michael@0: device->path.string(), device->identifier.name.string(), device->id, michael@0: device->fd, device->classes); michael@0: michael@0: if (device->id == mBuiltInKeyboardId) { michael@0: ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this", michael@0: device->path.string(), mBuiltInKeyboardId); michael@0: mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD; michael@0: } michael@0: michael@0: if (!device->isVirtual()) { michael@0: if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) { michael@0: ALOGW("Could not remove device fd from epoll instance. errno=%d", errno); michael@0: } michael@0: } michael@0: michael@0: mDevices.removeItem(device->id); michael@0: device->close(); michael@0: michael@0: // Unlink for opening devices list if it is present. michael@0: Device* pred = NULL; michael@0: bool found = false; michael@0: for (Device* entry = mOpeningDevices; entry != NULL; ) { michael@0: if (entry == device) { michael@0: found = true; michael@0: break; michael@0: } michael@0: pred = entry; michael@0: entry = entry->next; michael@0: } michael@0: if (found) { michael@0: // Unlink the device from the opening devices list then delete it. michael@0: // We don't need to tell the client that the device was closed because michael@0: // it does not even know it was opened in the first place. michael@0: ALOGI("Device %s was immediately closed after opening.", device->path.string()); michael@0: if (pred) { michael@0: pred->next = device->next; michael@0: } else { michael@0: mOpeningDevices = device->next; michael@0: } michael@0: delete device; michael@0: } else { michael@0: // Link into closing devices list. michael@0: // The device will be deleted later after we have informed the client. michael@0: device->next = mClosingDevices; michael@0: mClosingDevices = device; michael@0: } michael@0: } michael@0: michael@0: status_t EventHub::readNotifyLocked() { michael@0: int res; michael@0: char devname[PATH_MAX]; michael@0: char *filename; michael@0: char event_buf[512]; michael@0: int event_size; michael@0: int event_pos = 0; michael@0: struct inotify_event *event; michael@0: michael@0: ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd); michael@0: res = read(mINotifyFd, event_buf, sizeof(event_buf)); michael@0: if(res < (int)sizeof(*event)) { michael@0: if(errno == EINTR) michael@0: return 0; michael@0: ALOGW("could not get event, %s\n", strerror(errno)); michael@0: return -1; michael@0: } michael@0: //printf("got %d bytes of event information\n", res); michael@0: michael@0: strcpy(devname, DEVICE_PATH); michael@0: filename = devname + strlen(devname); michael@0: *filename++ = '/'; michael@0: michael@0: while(res >= (int)sizeof(*event)) { michael@0: event = (struct inotify_event *)(event_buf + event_pos); michael@0: //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : ""); michael@0: if(event->len) { michael@0: strcpy(filename, event->name); michael@0: if(event->mask & IN_CREATE) { michael@0: openDeviceLocked(devname); michael@0: } else { michael@0: ALOGI("Removing device '%s' due to inotify event\n", devname); michael@0: closeDeviceByPathLocked(devname); michael@0: } michael@0: } michael@0: event_size = sizeof(*event) + event->len; michael@0: res -= event_size; michael@0: event_pos += event_size; michael@0: } michael@0: return 0; michael@0: } michael@0: michael@0: status_t EventHub::scanDirLocked(const char *dirname) michael@0: { michael@0: char devname[PATH_MAX]; michael@0: char *filename; michael@0: DIR *dir; michael@0: struct dirent *de; michael@0: dir = opendir(dirname); michael@0: if(dir == NULL) michael@0: return -1; michael@0: strcpy(devname, dirname); michael@0: filename = devname + strlen(devname); michael@0: *filename++ = '/'; michael@0: while((de = readdir(dir))) { michael@0: if(de->d_name[0] == '.' && michael@0: (de->d_name[1] == '\0' || michael@0: (de->d_name[1] == '.' && de->d_name[2] == '\0'))) michael@0: continue; michael@0: strcpy(filename, de->d_name); michael@0: openDeviceLocked(devname); michael@0: } michael@0: closedir(dir); michael@0: return 0; michael@0: } michael@0: michael@0: void EventHub::requestReopenDevices() { michael@0: ALOGV("requestReopenDevices() called"); michael@0: michael@0: AutoMutex _l(mLock); michael@0: mNeedToReopenDevices = true; michael@0: } michael@0: michael@0: void EventHub::dump(String8& dump) { michael@0: dump.append("Event Hub State:\n"); michael@0: michael@0: { // acquire lock michael@0: AutoMutex _l(mLock); michael@0: michael@0: dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId); michael@0: michael@0: dump.append(INDENT "Devices:\n"); michael@0: michael@0: for (size_t i = 0; i < mDevices.size(); i++) { michael@0: const Device* device = mDevices.valueAt(i); michael@0: if (mBuiltInKeyboardId == device->id) { michael@0: dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n", michael@0: device->id, device->identifier.name.string()); michael@0: } else { michael@0: dump.appendFormat(INDENT2 "%d: %s\n", device->id, michael@0: device->identifier.name.string()); michael@0: } michael@0: dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes); michael@0: dump.appendFormat(INDENT3 "Path: %s\n", device->path.string()); michael@0: dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string()); michael@0: dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string()); michael@0: dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string()); michael@0: dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, " michael@0: "product=0x%04x, version=0x%04x\n", michael@0: device->identifier.bus, device->identifier.vendor, michael@0: device->identifier.product, device->identifier.version); michael@0: dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n", michael@0: device->keyMap.keyLayoutFile.string()); michael@0: dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n", michael@0: device->keyMap.keyCharacterMapFile.string()); michael@0: dump.appendFormat(INDENT3 "ConfigurationFile: %s\n", michael@0: device->configurationFile.string()); michael@0: dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n", michael@0: toString(device->overlayKeyMap != NULL)); michael@0: } michael@0: } // release lock michael@0: } michael@0: michael@0: void EventHub::monitor() { michael@0: // Acquire and release the lock to ensure that the event hub has not deadlocked. michael@0: mLock.lock(); michael@0: mLock.unlock(); michael@0: } michael@0: michael@0: michael@0: }; // namespace android