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