EventHub.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  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. #include <assert.h>
  17. #include <dirent.h>
  18. #include <errno.h>
  19. #include <fcntl.h>
  20. #include <inttypes.h>
  21. #include <memory.h>
  22. #include <stdint.h>
  23. #include <stdio.h>
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #include <sys/epoll.h>
  27. #include <sys/limits.h>
  28. #include <sys/inotify.h>
  29. #include <sys/ioctl.h>
  30. #include <sys/utsname.h>
  31. #include <unistd.h>
  32. #define LOG_TAG "EventHub"
  33. // #define LOG_NDEBUG 0
  34. #include "EventHub.h"
  35. #include <hardware_legacy/power.h>
  36. #include <cutils/properties.h>
  37. #include <openssl/sha.h>
  38. #include <utils/Log.h>
  39. #include <utils/Timers.h>
  40. #include <utils/threads.h>
  41. #include <utils/Errors.h>
  42. #include <input/KeyLayoutMap.h>
  43. #include <input/KeyCharacterMap.h>
  44. #include <input/VirtualKeyMap.h>
  45. /* this macro is used to tell if "bit" is set in "array"
  46. * it selects a byte from the array, and does a boolean AND
  47. * operation with a byte that only has the relevant bit set.
  48. * eg. to check for the 12th bit, we do (array[1] & 1<<4)
  49. */
  50. #define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
  51. /* this macro computes the number of bytes needed to represent a bit array of the specified size */
  52. #define sizeof_bit_array(bits) ((bits + 7) / 8)
  53. #define INDENT " "
  54. #define INDENT2 " "
  55. #define INDENT3 " "
  56. namespace android {
  57. static const char *WAKE_LOCK_ID = "KeyEvents";
  58. static const char *DEVICE_PATH = "/dev/input";
  59. /* return the larger integer */
  60. static inline int max(int v1, int v2)
  61. {
  62. return (v1 > v2) ? v1 : v2;
  63. }
  64. static inline const char* toString(bool value) {
  65. return value ? "true" : "false";
  66. }
  67. static String8 sha1(const String8& in) {
  68. SHA_CTX ctx;
  69. SHA1_Init(&ctx);
  70. SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
  71. u_char digest[SHA_DIGEST_LENGTH];
  72. SHA1_Final(digest, &ctx);
  73. String8 out;
  74. for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
  75. out.appendFormat("%02x", digest[i]);
  76. }
  77. return out;
  78. }
  79. static void getLinuxRelease(int* major, int* minor) {
  80. struct utsname info;
  81. if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
  82. *major = 0, *minor = 0;
  83. ALOGE("Could not get linux version: %s", strerror(errno));
  84. }
  85. }
  86. // --- Global Functions ---
  87. uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
  88. // Touch devices get dibs on touch-related axes.
  89. if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
  90. switch (axis) {
  91. case ABS_X:
  92. case ABS_Y:
  93. case ABS_PRESSURE:
  94. case ABS_TOOL_WIDTH:
  95. case ABS_DISTANCE:
  96. case ABS_TILT_X:
  97. case ABS_TILT_Y:
  98. case ABS_MT_SLOT:
  99. case ABS_MT_TOUCH_MAJOR:
  100. case ABS_MT_TOUCH_MINOR:
  101. case ABS_MT_WIDTH_MAJOR:
  102. case ABS_MT_WIDTH_MINOR:
  103. case ABS_MT_ORIENTATION:
  104. case ABS_MT_POSITION_X:
  105. case ABS_MT_POSITION_Y:
  106. case ABS_MT_TOOL_TYPE:
  107. case ABS_MT_BLOB_ID:
  108. case ABS_MT_TRACKING_ID:
  109. case ABS_MT_PRESSURE:
  110. case ABS_MT_DISTANCE:
  111. return INPUT_DEVICE_CLASS_TOUCH;
  112. }
  113. }
  114. // External stylus gets the pressure axis
  115. if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
  116. if (axis == ABS_PRESSURE) {
  117. return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
  118. }
  119. }
  120. // Joystick devices get the rest.
  121. return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
  122. }
  123. // --- EventHub::Device ---
  124. EventHub::Device::Device(int fd, int32_t id, const String8& path,
  125. const InputDeviceIdentifier& identifier) :
  126. next(NULL),
  127. fd(fd), id(id), path(path), identifier(identifier),
  128. classes(0), configuration(NULL), virtualKeyMap(NULL),
  129. ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
  130. timestampOverrideSec(0), timestampOverrideUsec(0) {
  131. memset(keyBitmask, 0, sizeof(keyBitmask));
  132. memset(absBitmask, 0, sizeof(absBitmask));
  133. memset(relBitmask, 0, sizeof(relBitmask));
  134. memset(swBitmask, 0, sizeof(swBitmask));
  135. memset(ledBitmask, 0, sizeof(ledBitmask));
  136. memset(ffBitmask, 0, sizeof(ffBitmask));
  137. memset(propBitmask, 0, sizeof(propBitmask));
  138. }
  139. EventHub::Device::~Device() {
  140. close();
  141. delete configuration;
  142. delete virtualKeyMap;
  143. }
  144. void EventHub::Device::close() {
  145. if (fd >= 0) {
  146. ::close(fd);
  147. fd = -1;
  148. }
  149. }
  150. // --- EventHub ---
  151. const uint32_t EventHub::EPOLL_ID_INOTIFY;
  152. const uint32_t EventHub::EPOLL_ID_WAKE;
  153. const int EventHub::EPOLL_SIZE_HINT;
  154. const int EventHub::EPOLL_MAX_EVENTS;
  155. EventHub::EventHub(void) :
  156. mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
  157. mOpeningDevices(0), mClosingDevices(0),
  158. mNeedToSendFinishedDeviceScan(false),
  159. mNeedToReopenDevices(false), mNeedToScanDevices(true),
  160. mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
  161. acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
  162. mEpollFd = epoll_create(EPOLL_SIZE_HINT);
  163. LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
  164. mINotifyFd = inotify_init();
  165. int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
  166. LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
  167. DEVICE_PATH, errno);
  168. struct epoll_event eventItem;
  169. memset(&eventItem, 0, sizeof(eventItem));
  170. eventItem.events = EPOLLIN;
  171. eventItem.data.u32 = EPOLL_ID_INOTIFY;
  172. result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
  173. LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
  174. int wakeFds[2];
  175. result = pipe(wakeFds);
  176. LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
  177. mWakeReadPipeFd = wakeFds[0];
  178. mWakeWritePipeFd = wakeFds[1];
  179. result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
  180. LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
  181. errno);
  182. result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
  183. LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
  184. errno);
  185. eventItem.data.u32 = EPOLL_ID_WAKE;
  186. result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
  187. LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
  188. errno);
  189. int major, minor;
  190. getLinuxRelease(&major, &minor);
  191. // EPOLLWAKEUP was introduced in kernel 3.5
  192. mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
  193. }
  194. EventHub::~EventHub(void) {
  195. closeAllDevicesLocked();
  196. while (mClosingDevices) {
  197. Device* device = mClosingDevices;
  198. mClosingDevices = device->next;
  199. delete device;
  200. }
  201. ::close(mEpollFd);
  202. ::close(mINotifyFd);
  203. ::close(mWakeReadPipeFd);
  204. ::close(mWakeWritePipeFd);
  205. release_wake_lock(WAKE_LOCK_ID);
  206. }
  207. InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
  208. AutoMutex _l(mLock);
  209. Device* device = getDeviceLocked(deviceId);
  210. if (device == NULL) return InputDeviceIdentifier();
  211. return device->identifier;
  212. }
  213. uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
  214. AutoMutex _l(mLock);
  215. Device* device = getDeviceLocked(deviceId);
  216. if (device == NULL) return 0;
  217. return device->classes;
  218. }
  219. int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
  220. AutoMutex _l(mLock);
  221. Device* device = getDeviceLocked(deviceId);
  222. if (device == NULL) return 0;
  223. return device->controllerNumber;
  224. }
  225. void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
  226. AutoMutex _l(mLock);
  227. Device* device = getDeviceLocked(deviceId);
  228. if (device && device->configuration) {
  229. *outConfiguration = *device->configuration;
  230. } else {
  231. outConfiguration->clear();
  232. }
  233. }
  234. status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
  235. RawAbsoluteAxisInfo* outAxisInfo) const {
  236. outAxisInfo->clear();
  237. if (axis >= 0 && axis <= ABS_MAX) {
  238. AutoMutex _l(mLock);
  239. Device* device = getDeviceLocked(deviceId);
  240. if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
  241. struct input_absinfo info;
  242. if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
  243. ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
  244. axis, device->identifier.name.string(), device->fd, errno);
  245. return -errno;
  246. }
  247. if (info.minimum != info.maximum) {
  248. outAxisInfo->valid = true;
  249. outAxisInfo->minValue = info.minimum;
  250. outAxisInfo->maxValue = info.maximum;
  251. outAxisInfo->flat = info.flat;
  252. outAxisInfo->fuzz = info.fuzz;
  253. outAxisInfo->resolution = info.resolution;
  254. }
  255. return OK;
  256. }
  257. }
  258. return -1;
  259. }
  260. bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
  261. if (axis >= 0 && axis <= REL_MAX) {
  262. AutoMutex _l(mLock);
  263. Device* device = getDeviceLocked(deviceId);
  264. if (device) {
  265. return test_bit(axis, device->relBitmask);
  266. }
  267. }
  268. return false;
  269. }
  270. bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
  271. if (property >= 0 && property <= INPUT_PROP_MAX) {
  272. AutoMutex _l(mLock);
  273. Device* device = getDeviceLocked(deviceId);
  274. if (device) {
  275. return test_bit(property, device->propBitmask);
  276. }
  277. }
  278. return false;
  279. }
  280. int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
  281. if (scanCode >= 0 && scanCode <= KEY_MAX) {
  282. AutoMutex _l(mLock);
  283. Device* device = getDeviceLocked(deviceId);
  284. if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
  285. uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
  286. memset(keyState, 0, sizeof(keyState));
  287. if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
  288. return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
  289. }
  290. }
  291. }
  292. return AKEY_STATE_UNKNOWN;
  293. }
  294. int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
  295. AutoMutex _l(mLock);
  296. Device* device = getDeviceLocked(deviceId);
  297. if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
  298. Vector<int32_t> scanCodes;
  299. device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
  300. if (scanCodes.size() != 0) {
  301. uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
  302. memset(keyState, 0, sizeof(keyState));
  303. if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
  304. for (size_t i = 0; i < scanCodes.size(); i++) {
  305. int32_t sc = scanCodes.itemAt(i);
  306. if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
  307. return AKEY_STATE_DOWN;
  308. }
  309. }
  310. return AKEY_STATE_UP;
  311. }
  312. }
  313. }
  314. return AKEY_STATE_UNKNOWN;
  315. }
  316. int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
  317. if (sw >= 0 && sw <= SW_MAX) {
  318. AutoMutex _l(mLock);
  319. Device* device = getDeviceLocked(deviceId);
  320. if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
  321. uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
  322. memset(swState, 0, sizeof(swState));
  323. if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
  324. return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
  325. }
  326. }
  327. }
  328. return AKEY_STATE_UNKNOWN;
  329. }
  330. status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
  331. *outValue = 0;
  332. if (axis >= 0 && axis <= ABS_MAX) {
  333. AutoMutex _l(mLock);
  334. Device* device = getDeviceLocked(deviceId);
  335. if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
  336. struct input_absinfo info;
  337. if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
  338. ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
  339. axis, device->identifier.name.string(), device->fd, errno);
  340. return -errno;
  341. }
  342. *outValue = info.value;
  343. return OK;
  344. }
  345. }
  346. return -1;
  347. }
  348. bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
  349. const int32_t* keyCodes, uint8_t* outFlags) const {
  350. AutoMutex _l(mLock);
  351. Device* device = getDeviceLocked(deviceId);
  352. if (device && device->keyMap.haveKeyLayout()) {
  353. Vector<int32_t> scanCodes;
  354. for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
  355. scanCodes.clear();
  356. status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
  357. keyCodes[codeIndex], &scanCodes);
  358. if (! err) {
  359. // check the possible scan codes identified by the layout map against the
  360. // map of codes actually emitted by the driver
  361. for (size_t sc = 0; sc < scanCodes.size(); sc++) {
  362. if (test_bit(scanCodes[sc], device->keyBitmask)) {
  363. outFlags[codeIndex] = 1;
  364. break;
  365. }
  366. }
  367. }
  368. }
  369. return true;
  370. }
  371. return false;
  372. }
  373. status_t EventHub::mapKey(int32_t deviceId,
  374. int32_t scanCode, int32_t usageCode, int32_t metaState,
  375. int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
  376. AutoMutex _l(mLock);
  377. Device* device = getDeviceLocked(deviceId);
  378. status_t status = NAME_NOT_FOUND;
  379. if (device) {
  380. // Check the key character map first.
  381. sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
  382. if (kcm != NULL) {
  383. if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
  384. *outFlags = 0;
  385. status = NO_ERROR;
  386. }
  387. }
  388. // Check the key layout next.
  389. if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
  390. if (!device->keyMap.keyLayoutMap->mapKey(
  391. scanCode, usageCode, outKeycode, outFlags)) {
  392. status = NO_ERROR;
  393. }
  394. }
  395. if (status == NO_ERROR) {
  396. if (kcm != NULL) {
  397. kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
  398. } else {
  399. *outMetaState = metaState;
  400. }
  401. }
  402. }
  403. if (status != NO_ERROR) {
  404. *outKeycode = 0;
  405. *outFlags = 0;
  406. *outMetaState = metaState;
  407. }
  408. return status;
  409. }
  410. status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
  411. AutoMutex _l(mLock);
  412. Device* device = getDeviceLocked(deviceId);
  413. if (device && device->keyMap.haveKeyLayout()) {
  414. status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
  415. if (err == NO_ERROR) {
  416. return NO_ERROR;
  417. }
  418. }
  419. return NAME_NOT_FOUND;
  420. }
  421. void EventHub::setExcludedDevices(const Vector<String8>& devices) {
  422. AutoMutex _l(mLock);
  423. mExcludedDevices = devices;
  424. }
  425. bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
  426. AutoMutex _l(mLock);
  427. Device* device = getDeviceLocked(deviceId);
  428. if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
  429. if (test_bit(scanCode, device->keyBitmask)) {
  430. return true;
  431. }
  432. }
  433. return false;
  434. }
  435. bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
  436. AutoMutex _l(mLock);
  437. Device* device = getDeviceLocked(deviceId);
  438. int32_t sc;
  439. if (device && mapLed(device, led, &sc) == NO_ERROR) {
  440. if (test_bit(sc, device->ledBitmask)) {
  441. return true;
  442. }
  443. }
  444. return false;
  445. }
  446. void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
  447. AutoMutex _l(mLock);
  448. Device* device = getDeviceLocked(deviceId);
  449. setLedStateLocked(device, led, on);
  450. }
  451. void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
  452. int32_t sc;
  453. if (device && !device->isVirtual() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
  454. struct input_event ev;
  455. ev.time.tv_sec = 0;
  456. ev.time.tv_usec = 0;
  457. ev.type = EV_LED;
  458. ev.code = sc;
  459. ev.value = on ? 1 : 0;
  460. ssize_t nWrite;
  461. do {
  462. nWrite = write(device->fd, &ev, sizeof(struct input_event));
  463. } while (nWrite == -1 && errno == EINTR);
  464. }
  465. }
  466. void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
  467. Vector<VirtualKeyDefinition>& outVirtualKeys) const {
  468. outVirtualKeys.clear();
  469. AutoMutex _l(mLock);
  470. Device* device = getDeviceLocked(deviceId);
  471. if (device && device->virtualKeyMap) {
  472. outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
  473. }
  474. }
  475. sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
  476. AutoMutex _l(mLock);
  477. Device* device = getDeviceLocked(deviceId);
  478. if (device) {
  479. return device->getKeyCharacterMap();
  480. }
  481. return NULL;
  482. }
  483. bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
  484. const sp<KeyCharacterMap>& map) {
  485. AutoMutex _l(mLock);
  486. Device* device = getDeviceLocked(deviceId);
  487. if (device) {
  488. if (map != device->overlayKeyMap) {
  489. device->overlayKeyMap = map;
  490. device->combinedKeyMap = KeyCharacterMap::combine(
  491. device->keyMap.keyCharacterMap, map);
  492. return true;
  493. }
  494. }
  495. return false;
  496. }
  497. static String8 generateDescriptor(InputDeviceIdentifier& identifier) {
  498. String8 rawDescriptor;
  499. rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor,
  500. identifier.product);
  501. // TODO add handling for USB devices to not uniqueify kbs that show up twice
  502. if (!identifier.uniqueId.isEmpty()) {
  503. rawDescriptor.append("uniqueId:");
  504. rawDescriptor.append(identifier.uniqueId);
  505. } else if (identifier.nonce != 0) {
  506. rawDescriptor.appendFormat("nonce:%04x", identifier.nonce);
  507. }
  508. if (identifier.vendor == 0 && identifier.product == 0) {
  509. // If we don't know the vendor and product id, then the device is probably
  510. // built-in so we need to rely on other information to uniquely identify
  511. // the input device. Usually we try to avoid relying on the device name or
  512. // location but for built-in input device, they are unlikely to ever change.
  513. if (!identifier.name.isEmpty()) {
  514. rawDescriptor.append("name:");
  515. rawDescriptor.append(identifier.name);
  516. } else if (!identifier.location.isEmpty()) {
  517. rawDescriptor.append("location:");
  518. rawDescriptor.append(identifier.location);
  519. }
  520. }
  521. identifier.descriptor = sha1(rawDescriptor);
  522. return rawDescriptor;
  523. }
  524. void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
  525. // Compute a device descriptor that uniquely identifies the device.
  526. // The descriptor is assumed to be a stable identifier. Its value should not
  527. // change between reboots, reconnections, firmware updates or new releases
  528. // of Android. In practice we sometimes get devices that cannot be uniquely
  529. // identified. In this case we enforce uniqueness between connected devices.
  530. // Ideally, we also want the descriptor to be short and relatively opaque.
  531. identifier.nonce = 0;
  532. String8 rawDescriptor = generateDescriptor(identifier);
  533. if (identifier.uniqueId.isEmpty()) {
  534. // If it didn't have a unique id check for conflicts and enforce
  535. // uniqueness if necessary.
  536. while(getDeviceByDescriptorLocked(identifier.descriptor) != NULL) {
  537. identifier.nonce++;
  538. rawDescriptor = generateDescriptor(identifier);
  539. }
  540. }
  541. ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
  542. identifier.descriptor.string());
  543. }
  544. void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
  545. AutoMutex _l(mLock);
  546. Device* device = getDeviceLocked(deviceId);
  547. if (device && !device->isVirtual()) {
  548. ff_effect effect;
  549. memset(&effect, 0, sizeof(effect));
  550. effect.type = FF_RUMBLE;
  551. effect.id = device->ffEffectId;
  552. effect.u.rumble.strong_magnitude = 0xc000;
  553. effect.u.rumble.weak_magnitude = 0xc000;
  554. effect.replay.length = (duration + 999999LL) / 1000000LL;
  555. effect.replay.delay = 0;
  556. if (ioctl(device->fd, EVIOCSFF, &effect)) {
  557. ALOGW("Could not upload force feedback effect to device %s due to error %d.",
  558. device->identifier.name.string(), errno);
  559. return;
  560. }
  561. device->ffEffectId = effect.id;
  562. struct input_event ev;
  563. ev.time.tv_sec = 0;
  564. ev.time.tv_usec = 0;
  565. ev.type = EV_FF;
  566. ev.code = device->ffEffectId;
  567. ev.value = 1;
  568. if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
  569. ALOGW("Could not start force feedback effect on device %s due to error %d.",
  570. device->identifier.name.string(), errno);
  571. return;
  572. }
  573. device->ffEffectPlaying = true;
  574. }
  575. }
  576. void EventHub::cancelVibrate(int32_t deviceId) {
  577. AutoMutex _l(mLock);
  578. Device* device = getDeviceLocked(deviceId);
  579. if (device && !device->isVirtual()) {
  580. if (device->ffEffectPlaying) {
  581. device->ffEffectPlaying = false;
  582. struct input_event ev;
  583. ev.time.tv_sec = 0;
  584. ev.time.tv_usec = 0;
  585. ev.type = EV_FF;
  586. ev.code = device->ffEffectId;
  587. ev.value = 0;
  588. if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
  589. ALOGW("Could not stop force feedback effect on device %s due to error %d.",
  590. device->identifier.name.string(), errno);
  591. return;
  592. }
  593. }
  594. }
  595. }
  596. EventHub::Device* EventHub::getDeviceByDescriptorLocked(String8& descriptor) const {
  597. size_t size = mDevices.size();
  598. for (size_t i = 0; i < size; i++) {
  599. Device* device = mDevices.valueAt(i);
  600. if (descriptor.compare(device->identifier.descriptor) == 0) {
  601. return device;
  602. }
  603. }
  604. return NULL;
  605. }
  606. EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
  607. if (deviceId == BUILT_IN_KEYBOARD_ID) {
  608. deviceId = mBuiltInKeyboardId;
  609. }
  610. ssize_t index = mDevices.indexOfKey(deviceId);
  611. return index >= 0 ? mDevices.valueAt(index) : NULL;
  612. }
  613. EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
  614. for (size_t i = 0; i < mDevices.size(); i++) {
  615. Device* device = mDevices.valueAt(i);
  616. if (device->path == devicePath) {
  617. return device;
  618. }
  619. }
  620. return NULL;
  621. }
  622. size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
  623. ALOG_ASSERT(bufferSize >= 1);
  624. AutoMutex _l(mLock);
  625. struct input_event readBuffer[bufferSize];
  626. RawEvent* event = buffer;
  627. size_t capacity = bufferSize;
  628. bool awoken = false;
  629. for (;;) {
  630. nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
  631. // Reopen input devices if needed.
  632. if (mNeedToReopenDevices) {
  633. mNeedToReopenDevices = false;
  634. ALOGI("Reopening all input devices due to a configuration change.");
  635. closeAllDevicesLocked();
  636. mNeedToScanDevices = true;
  637. break; // return to the caller before we actually rescan
  638. }
  639. // Report any devices that had last been added/removed.
  640. while (mClosingDevices) {
  641. Device* device = mClosingDevices;
  642. ALOGV("Reporting device closed: id=%d, name=%s\n",
  643. device->id, device->path.string());
  644. mClosingDevices = device->next;
  645. event->when = now;
  646. event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
  647. event->type = DEVICE_REMOVED;
  648. event += 1;
  649. delete device;
  650. mNeedToSendFinishedDeviceScan = true;
  651. if (--capacity == 0) {
  652. break;
  653. }
  654. }
  655. if (mNeedToScanDevices) {
  656. mNeedToScanDevices = false;
  657. scanDevicesLocked();
  658. mNeedToSendFinishedDeviceScan = true;
  659. }
  660. while (mOpeningDevices != NULL) {
  661. Device* device = mOpeningDevices;
  662. ALOGV("Reporting device opened: id=%d, name=%s\n",
  663. device->id, device->path.string());
  664. mOpeningDevices = device->next;
  665. event->when = now;
  666. event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
  667. event->type = DEVICE_ADDED;
  668. event += 1;
  669. mNeedToSendFinishedDeviceScan = true;
  670. if (--capacity == 0) {
  671. break;
  672. }
  673. }
  674. if (mNeedToSendFinishedDeviceScan) {
  675. mNeedToSendFinishedDeviceScan = false;
  676. event->when = now;
  677. event->type = FINISHED_DEVICE_SCAN;
  678. event += 1;
  679. if (--capacity == 0) {
  680. break;
  681. }
  682. }
  683. // Grab the next input event.
  684. bool deviceChanged = false;
  685. while (mPendingEventIndex < mPendingEventCount) {
  686. const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
  687. if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
  688. if (eventItem.events & EPOLLIN) {
  689. mPendingINotify = true;
  690. } else {
  691. ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
  692. }
  693. continue;
  694. }
  695. if (eventItem.data.u32 == EPOLL_ID_WAKE) {
  696. if (eventItem.events & EPOLLIN) {
  697. ALOGV("awoken after wake()");
  698. awoken = true;
  699. char buffer[16];
  700. ssize_t nRead;
  701. do {
  702. nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
  703. } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
  704. } else {
  705. ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
  706. eventItem.events);
  707. }
  708. continue;
  709. }
  710. ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
  711. if (deviceIndex < 0) {
  712. ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
  713. eventItem.events, eventItem.data.u32);
  714. continue;
  715. }
  716. Device* device = mDevices.valueAt(deviceIndex);
  717. if (eventItem.events & EPOLLIN) {
  718. int32_t readSize = read(device->fd, readBuffer,
  719. sizeof(struct input_event) * capacity);
  720. if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
  721. // Device was removed before INotify noticed.
  722. ALOGW("could not get event, removed? (fd: %d size: %" PRId32
  723. " bufferSize: %zu capacity: %zu errno: %d)\n",
  724. device->fd, readSize, bufferSize, capacity, errno);
  725. deviceChanged = true;
  726. closeDeviceLocked(device);
  727. } else if (readSize < 0) {
  728. if (errno != EAGAIN && errno != EINTR) {
  729. ALOGW("could not get event (errno=%d)", errno);
  730. }
  731. } else if ((readSize % sizeof(struct input_event)) != 0) {
  732. ALOGE("could not get event (wrong size: %d)", readSize);
  733. } else {
  734. int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
  735. size_t count = size_t(readSize) / sizeof(struct input_event);
  736. for (size_t i = 0; i < count; i++) {
  737. struct input_event& iev = readBuffer[i];
  738. ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
  739. device->path.string(),
  740. (int) iev.time.tv_sec, (int) iev.time.tv_usec,
  741. iev.type, iev.code, iev.value);
  742. // Some input devices may have a better concept of the time
  743. // when an input event was actually generated than the kernel
  744. // which simply timestamps all events on entry to evdev.
  745. // This is a custom Android extension of the input protocol
  746. // mainly intended for use with uinput based device drivers.
  747. if (iev.type == EV_MSC) {
  748. if (iev.code == MSC_ANDROID_TIME_SEC) {
  749. device->timestampOverrideSec = iev.value;
  750. continue;
  751. } else if (iev.code == MSC_ANDROID_TIME_USEC) {
  752. device->timestampOverrideUsec = iev.value;
  753. continue;
  754. }
  755. }
  756. if (device->timestampOverrideSec || device->timestampOverrideUsec) {
  757. iev.time.tv_sec = device->timestampOverrideSec;
  758. iev.time.tv_usec = device->timestampOverrideUsec;
  759. if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
  760. device->timestampOverrideSec = 0;
  761. device->timestampOverrideUsec = 0;
  762. }
  763. ALOGV("applied override time %d.%06d",
  764. int(iev.time.tv_sec), int(iev.time.tv_usec));
  765. }
  766. // Use the time specified in the event instead of the current time
  767. // so that downstream code can get more accurate estimates of
  768. // event dispatch latency from the time the event is enqueued onto
  769. // the evdev client buffer.
  770. //
  771. // The event's timestamp fortuitously uses the same monotonic clock
  772. // time base as the rest of Android. The kernel event device driver
  773. // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
  774. // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
  775. // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
  776. // system call that also queries ktime_get_ts().
  777. event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
  778. + nsecs_t(iev.time.tv_usec) * 1000LL;
  779. ALOGV("event time %" PRId64 ", now %" PRId64, event->when, now);
  780. // Bug 7291243: Add a guard in case the kernel generates timestamps
  781. // that appear to be far into the future because they were generated
  782. // using the wrong clock source.
  783. //
  784. // This can happen because when the input device is initially opened
  785. // it has a default clock source of CLOCK_REALTIME. Any input events
  786. // enqueued right after the device is opened will have timestamps
  787. // generated using CLOCK_REALTIME. We later set the clock source
  788. // to CLOCK_MONOTONIC but it is already too late.
  789. //
  790. // Invalid input event timestamps can result in ANRs, crashes and
  791. // and other issues that are hard to track down. We must not let them
  792. // propagate through the system.
  793. //
  794. // Log a warning so that we notice the problem and recover gracefully.
  795. if (event->when >= now + 10 * 1000000000LL) {
  796. // Double-check. Time may have moved on.
  797. nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
  798. if (event->when > time) {
  799. ALOGW("An input event from %s has a timestamp that appears to "
  800. "have been generated using the wrong clock source "
  801. "(expected CLOCK_MONOTONIC): "
  802. "event time %" PRId64 ", current time %" PRId64
  803. ", call time %" PRId64 ". "
  804. "Using current time instead.",
  805. device->path.string(), event->when, time, now);
  806. event->when = time;
  807. } else {
  808. ALOGV("Event time is ok but failed the fast path and required "
  809. "an extra call to systemTime: "
  810. "event time %" PRId64 ", current time %" PRId64
  811. ", call time %" PRId64 ".",
  812. event->when, time, now);
  813. }
  814. }
  815. event->deviceId = deviceId;
  816. event->type = iev.type;
  817. event->code = iev.code;
  818. event->value = iev.value;
  819. event += 1;
  820. capacity -= 1;
  821. }
  822. if (capacity == 0) {
  823. // The result buffer is full. Reset the pending event index
  824. // so we will try to read the device again on the next iteration.
  825. mPendingEventIndex -= 1;
  826. break;
  827. }
  828. }
  829. } else if (eventItem.events & EPOLLHUP) {
  830. ALOGI("Removing device %s due to epoll hang-up event.",
  831. device->identifier.name.string());
  832. deviceChanged = true;
  833. closeDeviceLocked(device);
  834. } else {
  835. ALOGW("Received unexpected epoll event 0x%08x for device %s.",
  836. eventItem.events, device->identifier.name.string());
  837. }
  838. }
  839. // readNotify() will modify the list of devices so this must be done after
  840. // processing all other events to ensure that we read all remaining events
  841. // before closing the devices.
  842. if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
  843. mPendingINotify = false;
  844. readNotifyLocked();
  845. deviceChanged = true;
  846. }
  847. // Report added or removed devices immediately.
  848. if (deviceChanged) {
  849. continue;
  850. }
  851. // Return now if we have collected any events or if we were explicitly awoken.
  852. if (event != buffer || awoken) {
  853. break;
  854. }
  855. // Poll for events. Mind the wake lock dance!
  856. // We hold a wake lock at all times except during epoll_wait(). This works due to some
  857. // subtle choreography. When a device driver has pending (unread) events, it acquires
  858. // a kernel wake lock. However, once the last pending event has been read, the device
  859. // driver will release the kernel wake lock. To prevent the system from going to sleep
  860. // when this happens, the EventHub holds onto its own user wake lock while the client
  861. // is processing events. Thus the system can only sleep if there are no events
  862. // pending or currently being processed.
  863. //
  864. // The timeout is advisory only. If the device is asleep, it will not wake just to
  865. // service the timeout.
  866. mPendingEventIndex = 0;
  867. mLock.unlock(); // release lock before poll, must be before release_wake_lock
  868. release_wake_lock(WAKE_LOCK_ID);
  869. int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
  870. acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
  871. mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
  872. if (pollResult == 0) {
  873. // Timed out.
  874. mPendingEventCount = 0;
  875. break;
  876. }
  877. if (pollResult < 0) {
  878. // An error occurred.
  879. mPendingEventCount = 0;
  880. // Sleep after errors to avoid locking up the system.
  881. // Hopefully the error is transient.
  882. if (errno != EINTR) {
  883. ALOGW("poll failed (errno=%d)\n", errno);
  884. usleep(100000);
  885. }
  886. } else {
  887. // Some events occurred.
  888. mPendingEventCount = size_t(pollResult);
  889. }
  890. }
  891. // All done, return the number of events we read.
  892. return event - buffer;
  893. }
  894. void EventHub::wake() {
  895. ALOGV("wake() called");
  896. ssize_t nWrite;
  897. do {
  898. nWrite = write(mWakeWritePipeFd, "W", 1);
  899. } while (nWrite == -1 && errno == EINTR);
  900. if (nWrite != 1 && errno != EAGAIN) {
  901. ALOGW("Could not write wake signal, errno=%d", errno);
  902. }
  903. }
  904. void EventHub::scanDevicesLocked() {
  905. status_t res = scanDirLocked(DEVICE_PATH);
  906. if(res < 0) {
  907. ALOGE("scan dir failed for %s\n", DEVICE_PATH);
  908. }
  909. if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
  910. createVirtualKeyboardLocked();
  911. }
  912. }
  913. // ----------------------------------------------------------------------------
  914. static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
  915. const uint8_t* end = array + endIndex;
  916. array += startIndex;
  917. while (array != end) {
  918. if (*(array++) != 0) {
  919. return true;
  920. }
  921. }
  922. return false;
  923. }
  924. static const int32_t GAMEPAD_KEYCODES[] = {
  925. AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
  926. AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
  927. AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
  928. AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
  929. AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
  930. AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
  931. };
  932. status_t EventHub::openDeviceLocked(const char *devicePath) {
  933. char buffer[80];
  934. ALOGV("Opening device: %s", devicePath);
  935. int fd = open(devicePath, O_RDWR | O_CLOEXEC);
  936. if(fd < 0) {
  937. ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
  938. return -1;
  939. }
  940. InputDeviceIdentifier identifier;
  941. // Get device name.
  942. if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
  943. //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
  944. } else {
  945. buffer[sizeof(buffer) - 1] = '\0';
  946. identifier.name.setTo(buffer);
  947. }
  948. // Check to see if the device is on our excluded list
  949. for (size_t i = 0; i < mExcludedDevices.size(); i++) {
  950. const String8& item = mExcludedDevices.itemAt(i);
  951. if (identifier.name == item) {
  952. ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
  953. close(fd);
  954. return -1;
  955. }
  956. }
  957. // Get device driver version.
  958. int driverVersion;
  959. if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
  960. ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
  961. close(fd);
  962. return -1;
  963. }
  964. // Get device identifier.
  965. struct input_id inputId;
  966. if(ioctl(fd, EVIOCGID, &inputId)) {
  967. ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
  968. close(fd);
  969. return -1;
  970. }
  971. identifier.bus = inputId.bustype;
  972. identifier.product = inputId.product;
  973. identifier.vendor = inputId.vendor;
  974. identifier.version = inputId.version;
  975. // Get device physical location.
  976. if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
  977. //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
  978. } else {
  979. buffer[sizeof(buffer) - 1] = '\0';
  980. identifier.location.setTo(buffer);
  981. }
  982. // Get device unique id.
  983. if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
  984. //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
  985. } else {
  986. buffer[sizeof(buffer) - 1] = '\0';
  987. identifier.uniqueId.setTo(buffer);
  988. }
  989. // Fill in the descriptor.
  990. assignDescriptorLocked(identifier);
  991. // Make file descriptor non-blocking for use with poll().
  992. if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
  993. ALOGE("Error %d making device file descriptor non-blocking.", errno);
  994. close(fd);
  995. return -1;
  996. }
  997. // Allocate device. (The device object takes ownership of the fd at this point.)
  998. int32_t deviceId = mNextDeviceId++;
  999. Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
  1000. ALOGV("add device %d: %s\n", deviceId, devicePath);
  1001. ALOGV(" bus: %04x\n"
  1002. " vendor %04x\n"
  1003. " product %04x\n"
  1004. " version %04x\n",
  1005. identifier.bus, identifier.vendor, identifier.product, identifier.version);
  1006. ALOGV(" name: \"%s\"\n", identifier.name.string());
  1007. ALOGV(" location: \"%s\"\n", identifier.location.string());
  1008. ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
  1009. ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
  1010. ALOGV(" driver: v%d.%d.%d\n",
  1011. driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
  1012. // Load the configuration file for the device.
  1013. loadConfigurationLocked(device);
  1014. // Figure out the kinds of events the device reports.
  1015. ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
  1016. ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
  1017. ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
  1018. ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
  1019. ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
  1020. ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
  1021. ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
  1022. // See if this is a keyboard. Ignore everything in the button range except for
  1023. // joystick and gamepad buttons which are handled like keyboards for the most part.
  1024. bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
  1025. || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
  1026. sizeof_bit_array(KEY_MAX + 1));
  1027. bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
  1028. sizeof_bit_array(BTN_MOUSE))
  1029. || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
  1030. sizeof_bit_array(BTN_DIGI));
  1031. if (haveKeyboardKeys || haveGamepadButtons) {
  1032. device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
  1033. }
  1034. // See if this is a cursor device such as a trackball or mouse.
  1035. if (test_bit(BTN_MOUSE, device->keyBitmask)
  1036. && test_bit(REL_X, device->relBitmask)
  1037. && test_bit(REL_Y, device->relBitmask)) {
  1038. device->classes |= INPUT_DEVICE_CLASS_CURSOR;
  1039. }
  1040. // See if this is a touch pad.
  1041. // Is this a new modern multi-touch driver?
  1042. if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
  1043. && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
  1044. // Some joysticks such as the PS3 controller report axes that conflict
  1045. // with the ABS_MT range. Try to confirm that the device really is
  1046. // a touch screen.
  1047. if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
  1048. device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
  1049. }
  1050. // Is this an old style single-touch driver?
  1051. } else if (test_bit(BTN_TOUCH, device->keyBitmask)
  1052. && test_bit(ABS_X, device->absBitmask)
  1053. && test_bit(ABS_Y, device->absBitmask)) {
  1054. device->classes |= INPUT_DEVICE_CLASS_TOUCH;
  1055. // Is this a BT stylus?
  1056. } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
  1057. test_bit(BTN_TOUCH, device->keyBitmask))
  1058. && !test_bit(ABS_X, device->absBitmask)
  1059. && !test_bit(ABS_Y, device->absBitmask)) {
  1060. device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
  1061. // Keyboard will try to claim some of the buttons but we really want to reserve those so we
  1062. // can fuse it with the touch screen data, so just take them back. Note this means an
  1063. // external stylus cannot also be a keyboard device.
  1064. device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
  1065. }
  1066. // See if this device is a joystick.
  1067. // Assumes that joysticks always have gamepad buttons in order to distinguish them
  1068. // from other devices such as accelerometers that also have absolute axes.
  1069. if (haveGamepadButtons) {
  1070. uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
  1071. for (int i = 0; i <= ABS_MAX; i++) {
  1072. if (test_bit(i, device->absBitmask)
  1073. && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
  1074. device->classes = assumedClasses;
  1075. break;
  1076. }
  1077. }
  1078. }
  1079. // Check whether this device has switches.
  1080. for (int i = 0; i <= SW_MAX; i++) {
  1081. if (test_bit(i, device->swBitmask)) {
  1082. device->classes |= INPUT_DEVICE_CLASS_SWITCH;
  1083. break;
  1084. }
  1085. }
  1086. // Check whether this device supports the vibrator.
  1087. if (test_bit(FF_RUMBLE, device->ffBitmask)) {
  1088. device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
  1089. }
  1090. // Configure virtual keys.
  1091. if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
  1092. // Load the virtual keys for the touch screen, if any.
  1093. // We do this now so that we can make sure to load the keymap if necessary.
  1094. status_t status = loadVirtualKeyMapLocked(device);
  1095. if (!status) {
  1096. device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
  1097. }
  1098. }
  1099. // Load the key map.
  1100. // We need to do this for joysticks too because the key layout may specify axes.
  1101. status_t keyMapStatus = NAME_NOT_FOUND;
  1102. if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
  1103. // Load the keymap for the device.
  1104. keyMapStatus = loadKeyMapLocked(device);
  1105. }
  1106. // Configure the keyboard, gamepad or virtual keyboard.
  1107. if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
  1108. // Register the keyboard as a built-in keyboard if it is eligible.
  1109. if (!keyMapStatus
  1110. && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
  1111. && isEligibleBuiltInKeyboard(device->identifier,
  1112. device->configuration, &device->keyMap)) {
  1113. mBuiltInKeyboardId = device->id;
  1114. }
  1115. // 'Q' key support = cheap test of whether this is an alpha-capable kbd
  1116. if (hasKeycodeLocked(device, AKEYCODE_Q)) {
  1117. device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
  1118. }
  1119. // See if this device has a DPAD.
  1120. if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
  1121. hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
  1122. hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
  1123. hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
  1124. hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
  1125. device->classes |= INPUT_DEVICE_CLASS_DPAD;
  1126. }
  1127. // See if this device has a gamepad.
  1128. for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
  1129. if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
  1130. device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
  1131. break;
  1132. }
  1133. }
  1134. // Disable kernel key repeat since we handle it ourselves
  1135. unsigned int repeatRate[] = {0,0};
  1136. if (ioctl(fd, EVIOCSREP, repeatRate)) {
  1137. ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno));
  1138. }
  1139. }
  1140. // If the device isn't recognized as something we handle, don't monitor it.
  1141. if (device->classes == 0) {
  1142. ALOGV("Dropping device: id=%d, path='%s', name='%s'",
  1143. deviceId, devicePath, device->identifier.name.string());
  1144. delete device;
  1145. return -1;
  1146. }
  1147. // Determine whether the device has a mic.
  1148. if (deviceHasMicLocked(device)) {
  1149. device->classes |= INPUT_DEVICE_CLASS_MIC;
  1150. }
  1151. // Determine whether the device is external or internal.
  1152. if (isExternalDeviceLocked(device)) {
  1153. device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
  1154. }
  1155. if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
  1156. && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
  1157. device->controllerNumber = getNextControllerNumberLocked(device);
  1158. setLedForController(device);
  1159. }
  1160. // Register with epoll.
  1161. struct epoll_event eventItem;
  1162. memset(&eventItem, 0, sizeof(eventItem));
  1163. eventItem.events = EPOLLIN;
  1164. if (mUsingEpollWakeup) {
  1165. eventItem.events |= EPOLLWAKEUP;
  1166. }
  1167. eventItem.data.u32 = deviceId;
  1168. if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
  1169. ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
  1170. delete device;
  1171. return -1;
  1172. }
  1173. String8 wakeMechanism("EPOLLWAKEUP");
  1174. if (!mUsingEpollWakeup) {
  1175. #ifndef EVIOCSSUSPENDBLOCK
  1176. // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
  1177. // will use an epoll flag instead, so as long as we want to support
  1178. // this feature, we need to be prepared to define the ioctl ourselves.
  1179. #define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
  1180. #endif
  1181. if (ioctl(fd, EVIOCSSUSPENDBLOCK, 1)) {
  1182. wakeMechanism = "<none>";
  1183. } else {
  1184. wakeMechanism = "EVIOCSSUSPENDBLOCK";
  1185. }
  1186. }
  1187. // Tell the kernel that we want to use the monotonic clock for reporting timestamps
  1188. // associated with input events. This is important because the input system
  1189. // uses the timestamps extensively and assumes they were recorded using the monotonic
  1190. // clock.
  1191. //
  1192. // In older kernel, before Linux 3.4, there was no way to tell the kernel which
  1193. // clock to use to input event timestamps. The standard kernel behavior was to
  1194. // record a real time timestamp, which isn't what we want. Android kernels therefore
  1195. // contained a patch to the evdev_event() function in drivers/input/evdev.c to
  1196. // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
  1197. // clock to be used instead of the real time clock.
  1198. //
  1199. // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
  1200. // Therefore, we no longer require the Android-specific kernel patch described above
  1201. // as long as we make sure to set select the monotonic clock. We do that here.
  1202. int clockId = CLOCK_MONOTONIC;
  1203. bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
  1204. ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
  1205. "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
  1206. "wakeMechanism=%s, usingClockIoctl=%s",
  1207. deviceId, fd, devicePath, device->identifier.name.string(),
  1208. device->classes,
  1209. device->configurationFile.string(),
  1210. device->keyMap.keyLayoutFile.string(),
  1211. device->keyMap.keyCharacterMapFile.string(),
  1212. toString(mBuiltInKeyboardId == deviceId),
  1213. wakeMechanism.string(), toString(usingClockIoctl));
  1214. addDeviceLocked(device);
  1215. return 0;
  1216. }
  1217. void EventHub::createVirtualKeyboardLocked() {
  1218. InputDeviceIdentifier identifier;
  1219. identifier.name = "Virtual";
  1220. identifier.uniqueId = "<virtual>";
  1221. assignDescriptorLocked(identifier);
  1222. Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
  1223. device->classes = INPUT_DEVICE_CLASS_KEYBOARD
  1224. | INPUT_DEVICE_CLASS_ALPHAKEY
  1225. | INPUT_DEVICE_CLASS_DPAD
  1226. | INPUT_DEVICE_CLASS_VIRTUAL;
  1227. loadKeyMapLocked(device);
  1228. addDeviceLocked(device);
  1229. }
  1230. void EventHub::addDeviceLocked(Device* device) {
  1231. mDevices.add(device->id, device);
  1232. device->next = mOpeningDevices;
  1233. mOpeningDevices = device;
  1234. }
  1235. void EventHub::loadConfigurationLocked(Device* device) {
  1236. device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
  1237. device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
  1238. if (device->configurationFile.isEmpty()) {
  1239. ALOGD("No input device configuration file found for device '%s'.",
  1240. device->identifier.name.string());
  1241. } else {
  1242. status_t status = PropertyMap::load(device->configurationFile,
  1243. &device->configuration);
  1244. if (status) {
  1245. ALOGE("Error loading input device configuration file for device '%s'. "
  1246. "Using default configuration.",
  1247. device->identifier.name.string());
  1248. }
  1249. }
  1250. }
  1251. status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
  1252. // The virtual key map is supplied by the kernel as a system board property file.
  1253. String8 path;
  1254. path.append("/sys/board_properties/virtualkeys.");
  1255. path.append(device->identifier.name);
  1256. if (access(path.string(), R_OK)) {
  1257. return NAME_NOT_FOUND;
  1258. }
  1259. return VirtualKeyMap::load(path, &device->virtualKeyMap);
  1260. }
  1261. status_t EventHub::loadKeyMapLocked(Device* device) {
  1262. return device->keyMap.load(device->identifier, device->configuration);
  1263. }
  1264. bool EventHub::isExternalDeviceLocked(Device* device) {
  1265. if (device->configuration) {
  1266. bool value;
  1267. if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
  1268. return !value;
  1269. }
  1270. }
  1271. return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
  1272. }
  1273. bool EventHub::deviceHasMicLocked(Device* device) {
  1274. if (device->configuration) {
  1275. bool value;
  1276. if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
  1277. return value;
  1278. }
  1279. }
  1280. return false;
  1281. }
  1282. int32_t EventHub::getNextControllerNumberLocked(Device* device) {
  1283. if (mControllerNumbers.isFull()) {
  1284. ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
  1285. device->identifier.name.string());
  1286. return 0;
  1287. }
  1288. // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
  1289. // one
  1290. return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
  1291. }
  1292. void EventHub::releaseControllerNumberLocked(Device* device) {
  1293. int32_t num = device->controllerNumber;
  1294. device->controllerNumber= 0;
  1295. if (num == 0) {
  1296. return;
  1297. }
  1298. mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
  1299. }
  1300. void EventHub::setLedForController(Device* device) {
  1301. for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
  1302. setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
  1303. }
  1304. }
  1305. bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
  1306. if (!device->keyMap.haveKeyLayout()) {
  1307. return false;
  1308. }
  1309. Vector<int32_t> scanCodes;
  1310. device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
  1311. const size_t N = scanCodes.size();
  1312. for (size_t i=0; i<N && i<=KEY_MAX; i++) {
  1313. int32_t sc = scanCodes.itemAt(i);
  1314. if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
  1315. return true;
  1316. }
  1317. }
  1318. return false;
  1319. }
  1320. status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
  1321. if (!device->keyMap.haveKeyLayout()) {
  1322. return NAME_NOT_FOUND;
  1323. }
  1324. int32_t scanCode;
  1325. if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
  1326. if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
  1327. *outScanCode = scanCode;
  1328. return NO_ERROR;
  1329. }
  1330. }
  1331. return NAME_NOT_FOUND;
  1332. }
  1333. status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
  1334. Device* device = getDeviceByPathLocked(devicePath);
  1335. if (device) {
  1336. closeDeviceLocked(device);
  1337. return 0;
  1338. }
  1339. ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
  1340. return -1;
  1341. }
  1342. void EventHub::closeAllDevicesLocked() {
  1343. while (mDevices.size() > 0) {
  1344. closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
  1345. }
  1346. }
  1347. void EventHub::closeDeviceLocked(Device* device) {
  1348. ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
  1349. device->path.string(), device->identifier.name.string(), device->id,
  1350. device->fd, device->classes);
  1351. if (device->id == mBuiltInKeyboardId) {
  1352. ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
  1353. device->path.string(), mBuiltInKeyboardId);
  1354. mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
  1355. }
  1356. if (!device->isVirtual()) {
  1357. if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
  1358. ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
  1359. }
  1360. }
  1361. releaseControllerNumberLocked(device);
  1362. mDevices.removeItem(device->id);
  1363. device->close();
  1364. // Unlink for opening devices list if it is present.
  1365. Device* pred = NULL;
  1366. bool found = false;
  1367. for (Device* entry = mOpeningDevices; entry != NULL; ) {
  1368. if (entry == device) {
  1369. found = true;
  1370. break;
  1371. }
  1372. pred = entry;
  1373. entry = entry->next;
  1374. }
  1375. if (found) {
  1376. // Unlink the device from the opening devices list then delete it.
  1377. // We don't need to tell the client that the device was closed because
  1378. // it does not even know it was opened in the first place.
  1379. ALOGI("Device %s was immediately closed after opening.", device->path.string());
  1380. if (pred) {
  1381. pred->next = device->next;
  1382. } else {
  1383. mOpeningDevices = device->next;
  1384. }
  1385. delete device;
  1386. } else {
  1387. // Link into closing devices list.
  1388. // The device will be deleted later after we have informed the client.
  1389. device->next = mClosingDevices;
  1390. mClosingDevices = device;
  1391. }
  1392. }
  1393. status_t EventHub::readNotifyLocked() {
  1394. int res;
  1395. char devname[PATH_MAX];
  1396. char *filename;
  1397. char event_buf[512];
  1398. int event_size;
  1399. int event_pos = 0;
  1400. struct inotify_event *event;
  1401. ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
  1402. res = read(mINotifyFd, event_buf, sizeof(event_buf));
  1403. if(res < (int)sizeof(*event)) {
  1404. if(errno == EINTR)
  1405. return 0;
  1406. ALOGW("could not get event, %s\n", strerror(errno));
  1407. return -1;
  1408. }
  1409. //printf("got %d bytes of event information\n", res);
  1410. strcpy(devname, DEVICE_PATH);
  1411. filename = devname + strlen(devname);
  1412. *filename++ = '/';
  1413. while(res >= (int)sizeof(*event)) {
  1414. event = (struct inotify_event *)(event_buf + event_pos);
  1415. //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
  1416. if(event->len) {
  1417. strcpy(filename, event->name);
  1418. if(event->mask & IN_CREATE) {
  1419. openDeviceLocked(devname);
  1420. } else {
  1421. ALOGI("Removing device '%s' due to inotify event\n", devname);
  1422. closeDeviceByPathLocked(devname);
  1423. }
  1424. }
  1425. event_size = sizeof(*event) + event->len;
  1426. res -= event_size;
  1427. event_pos += event_size;
  1428. }
  1429. return 0;
  1430. }
  1431. status_t EventHub::scanDirLocked(const char *dirname)
  1432. {
  1433. char devname[PATH_MAX];
  1434. char *filename;
  1435. DIR *dir;
  1436. struct dirent *de;
  1437. dir = opendir(dirname);
  1438. if(dir == NULL)
  1439. return -1;
  1440. strcpy(devname, dirname);
  1441. filename = devname + strlen(devname);
  1442. *filename++ = '/';
  1443. while((de = readdir(dir))) {
  1444. if(de->d_name[0] == '.' &&
  1445. (de->d_name[1] == '\0' ||
  1446. (de->d_name[1] == '.' && de->d_name[2] == '\0')))
  1447. continue;
  1448. strcpy(filename, de->d_name);
  1449. openDeviceLocked(devname);
  1450. }
  1451. closedir(dir);
  1452. return 0;
  1453. }
  1454. void EventHub::requestReopenDevices() {
  1455. ALOGV("requestReopenDevices() called");
  1456. AutoMutex _l(mLock);
  1457. mNeedToReopenDevices = true;
  1458. }
  1459. void EventHub::dump(String8& dump) {
  1460. dump.append("Event Hub State:\n");
  1461. { // acquire lock
  1462. AutoMutex _l(mLock);
  1463. dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
  1464. dump.append(INDENT "Devices:\n");
  1465. for (size_t i = 0; i < mDevices.size(); i++) {
  1466. const Device* device = mDevices.valueAt(i);
  1467. if (mBuiltInKeyboardId == device->id) {
  1468. dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
  1469. device->id, device->identifier.name.string());
  1470. } else {
  1471. dump.appendFormat(INDENT2 "%d: %s\n", device->id,
  1472. device->identifier.name.string());
  1473. }
  1474. dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
  1475. dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
  1476. dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
  1477. dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
  1478. dump.appendFormat(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
  1479. dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
  1480. dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
  1481. "product=0x%04x, version=0x%04x\n",
  1482. device->identifier.bus, device->identifier.vendor,
  1483. device->identifier.product, device->identifier.version);
  1484. dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
  1485. device->keyMap.keyLayoutFile.string());
  1486. dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
  1487. device->keyMap.keyCharacterMapFile.string());
  1488. dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
  1489. device->configurationFile.string());
  1490. dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
  1491. toString(device->overlayKeyMap != NULL));
  1492. }
  1493. } // release lock
  1494. }
  1495. void EventHub::monitor() {
  1496. // Acquire and release the lock to ensure that the event hub has not deadlocked.
  1497. mLock.lock();
  1498. mLock.unlock();
  1499. }
  1500. }; // namespace android