blob: fab091f9617d573ea70f7c4808f11801798e5614 [file] [log] [blame]
Jeff Brownb4ff35d2011-01-02 16:37:43 -08001/*
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080017#define LOG_TAG "EventHub"
18
JP Abgrall25a465b2012-05-16 10:33:49 -070019// #define LOG_NDEBUG 0
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020
Jeff Brownb4ff35d2011-01-02 16:37:43 -080021#include "EventHub.h"
22
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080023#include <hardware_legacy/power.h>
24
25#include <cutils/properties.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026#include <utils/Log.h>
27#include <utils/Timers.h>
Mathias Agopian3b4062e2009-05-31 19:13:00 -070028#include <utils/threads.h>
Mathias Agopian3b4062e2009-05-31 19:13:00 -070029#include <utils/Errors.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030
31#include <stdlib.h>
32#include <stdio.h>
33#include <unistd.h>
34#include <fcntl.h>
35#include <memory.h>
36#include <errno.h>
37#include <assert.h>
38
Jeff Brown9d3b1a42013-07-01 19:07:15 -070039#include <input/KeyLayoutMap.h>
40#include <input/KeyCharacterMap.h>
41#include <input/VirtualKeyMap.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042
43#include <string.h>
44#include <stdint.h>
45#include <dirent.h>
Jeff Brown93fa9b32011-06-14 17:09:25 -070046
47#include <sys/inotify.h>
48#include <sys/epoll.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049#include <sys/ioctl.h>
Jeff Brown93fa9b32011-06-14 17:09:25 -070050#include <sys/limits.h>
Jeff Brown4dac9012013-04-10 01:03:19 -070051#include <sys/sha1.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052
53/* this macro is used to tell if "bit" is set in "array"
54 * it selects a byte from the array, and does a boolean AND
55 * operation with a byte that only has the relevant bit set.
56 * eg. to check for the 12th bit, we do (array[1] & 1<<4)
57 */
58#define test_bit(bit, array) (array[bit/8] & (1<<(bit%8)))
59
Jeff Brownfd035822010-06-30 16:10:35 -070060/* this macro computes the number of bytes needed to represent a bit array of the specified size */
61#define sizeof_bit_array(bits) ((bits + 7) / 8)
62
Jeff Brownf2f48712010-10-01 17:46:21 -070063#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067namespace android {
68
69static const char *WAKE_LOCK_ID = "KeyEvents";
Jeff Brown90655042010-12-02 13:50:46 -080070static const char *DEVICE_PATH = "/dev/input";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
72/* return the larger integer */
73static inline int max(int v1, int v2)
74{
75 return (v1 > v2) ? v1 : v2;
76}
77
Jeff Brownf2f48712010-10-01 17:46:21 -070078static inline const char* toString(bool value) {
79 return value ? "true" : "false";
80}
81
Jeff Browne38fdfa2012-04-06 14:51:01 -070082static String8 sha1(const String8& in) {
83 SHA1_CTX ctx;
84 SHA1Init(&ctx);
85 SHA1Update(&ctx, reinterpret_cast<const u_char*>(in.string()), in.size());
86 u_char digest[SHA1_DIGEST_LENGTH];
87 SHA1Final(digest, &ctx);
88
89 String8 out;
90 for (size_t i = 0; i < SHA1_DIGEST_LENGTH; i++) {
91 out.appendFormat("%02x", digest[i]);
92 }
93 return out;
94}
95
Jeff Brown9f25b7f2012-04-10 14:30:49 -070096static void setDescriptor(InputDeviceIdentifier& identifier) {
97 // Compute a device descriptor that uniquely identifies the device.
98 // The descriptor is assumed to be a stable identifier. Its value should not
99 // change between reboots, reconnections, firmware updates or new releases of Android.
100 // Ideally, we also want the descriptor to be short and relatively opaque.
101 String8 rawDescriptor;
102 rawDescriptor.appendFormat(":%04x:%04x:", identifier.vendor, identifier.product);
103 if (!identifier.uniqueId.isEmpty()) {
104 rawDescriptor.append("uniqueId:");
105 rawDescriptor.append(identifier.uniqueId);
106 } if (identifier.vendor == 0 && identifier.product == 0) {
107 // If we don't know the vendor and product id, then the device is probably
108 // built-in so we need to rely on other information to uniquely identify
109 // the input device. Usually we try to avoid relying on the device name or
110 // location but for built-in input device, they are unlikely to ever change.
111 if (!identifier.name.isEmpty()) {
112 rawDescriptor.append("name:");
113 rawDescriptor.append(identifier.name);
114 } else if (!identifier.location.isEmpty()) {
115 rawDescriptor.append("location:");
116 rawDescriptor.append(identifier.location);
117 }
118 }
119 identifier.descriptor = sha1(rawDescriptor);
Jeff Brown49ccac52012-04-11 18:27:33 -0700120 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.string(),
121 identifier.descriptor.string());
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700122}
123
Jeff Brown9ee285a2011-08-31 12:56:34 -0700124// --- Global Functions ---
125
126uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
127 // Touch devices get dibs on touch-related axes.
128 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
129 switch (axis) {
130 case ABS_X:
131 case ABS_Y:
132 case ABS_PRESSURE:
133 case ABS_TOOL_WIDTH:
134 case ABS_DISTANCE:
135 case ABS_TILT_X:
136 case ABS_TILT_Y:
137 case ABS_MT_SLOT:
138 case ABS_MT_TOUCH_MAJOR:
139 case ABS_MT_TOUCH_MINOR:
140 case ABS_MT_WIDTH_MAJOR:
141 case ABS_MT_WIDTH_MINOR:
142 case ABS_MT_ORIENTATION:
143 case ABS_MT_POSITION_X:
144 case ABS_MT_POSITION_Y:
145 case ABS_MT_TOOL_TYPE:
146 case ABS_MT_BLOB_ID:
147 case ABS_MT_TRACKING_ID:
148 case ABS_MT_PRESSURE:
149 case ABS_MT_DISTANCE:
150 return INPUT_DEVICE_CLASS_TOUCH;
151 }
152 }
153
154 // Joystick devices get the rest.
155 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
156}
157
Jeff Brown90655042010-12-02 13:50:46 -0800158// --- EventHub::Device ---
159
160EventHub::Device::Device(int fd, int32_t id, const String8& path,
161 const InputDeviceIdentifier& identifier) :
162 next(NULL),
163 fd(fd), id(id), path(path), identifier(identifier),
Jeff Browna47425a2012-04-13 04:09:27 -0700164 classes(0), configuration(NULL), virtualKeyMap(NULL),
Jeff Brown4dac9012013-04-10 01:03:19 -0700165 ffEffectPlaying(false), ffEffectId(-1),
166 timestampOverrideSec(0), timestampOverrideUsec(0) {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700167 memset(keyBitmask, 0, sizeof(keyBitmask));
168 memset(absBitmask, 0, sizeof(absBitmask));
169 memset(relBitmask, 0, sizeof(relBitmask));
170 memset(swBitmask, 0, sizeof(swBitmask));
171 memset(ledBitmask, 0, sizeof(ledBitmask));
Jeff Browna47425a2012-04-13 04:09:27 -0700172 memset(ffBitmask, 0, sizeof(ffBitmask));
Jeff Brown93fa9b32011-06-14 17:09:25 -0700173 memset(propBitmask, 0, sizeof(propBitmask));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174}
175
Jeff Brown90655042010-12-02 13:50:46 -0800176EventHub::Device::~Device() {
177 close();
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800178 delete configuration;
Jeff Brown90655042010-12-02 13:50:46 -0800179 delete virtualKeyMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180}
181
Jeff Brown90655042010-12-02 13:50:46 -0800182void EventHub::Device::close() {
183 if (fd >= 0) {
184 ::close(fd);
185 fd = -1;
186 }
187}
188
189
190// --- EventHub ---
191
Jeff Brown93fa9b32011-06-14 17:09:25 -0700192const uint32_t EventHub::EPOLL_ID_INOTIFY;
193const uint32_t EventHub::EPOLL_ID_WAKE;
194const int EventHub::EPOLL_SIZE_HINT;
195const int EventHub::EPOLL_MAX_EVENTS;
196
Jeff Brown90655042010-12-02 13:50:46 -0800197EventHub::EventHub(void) :
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700198 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1),
Jeff Brown90655042010-12-02 13:50:46 -0800199 mOpeningDevices(0), mClosingDevices(0),
Jeff Brown93fa9b32011-06-14 17:09:25 -0700200 mNeedToSendFinishedDeviceScan(false),
201 mNeedToReopenDevices(false), mNeedToScanDevices(true),
202 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
Jeff Brownb7198742011-03-18 18:14:26 -0700204
Jeff Brown93fa9b32011-06-14 17:09:25 -0700205 mEpollFd = epoll_create(EPOLL_SIZE_HINT);
206 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
207
208 mINotifyFd = inotify_init();
209 int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
210 LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
211 DEVICE_PATH, errno);
212
213 struct epoll_event eventItem;
214 memset(&eventItem, 0, sizeof(eventItem));
215 eventItem.events = EPOLLIN;
216 eventItem.data.u32 = EPOLL_ID_INOTIFY;
217 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
218 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
219
220 int wakeFds[2];
221 result = pipe(wakeFds);
222 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
223
224 mWakeReadPipeFd = wakeFds[0];
225 mWakeWritePipeFd = wakeFds[1];
226
227 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
228 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
229 errno);
230
231 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
232 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
233 errno);
234
235 eventItem.data.u32 = EPOLL_ID_WAKE;
236 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
237 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
238 errno);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239}
240
Jeff Brown90655042010-12-02 13:50:46 -0800241EventHub::~EventHub(void) {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700242 closeAllDevicesLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
Jeff Brown93fa9b32011-06-14 17:09:25 -0700244 while (mClosingDevices) {
245 Device* device = mClosingDevices;
246 mClosingDevices = device->next;
247 delete device;
248 }
249
250 ::close(mEpollFd);
251 ::close(mINotifyFd);
252 ::close(mWakeReadPipeFd);
253 ::close(mWakeWritePipeFd);
254
255 release_wake_lock(WAKE_LOCK_ID);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256}
257
Jeff Browne38fdfa2012-04-06 14:51:01 -0700258InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800260 Device* device = getDeviceLocked(deviceId);
Jeff Browne38fdfa2012-04-06 14:51:01 -0700261 if (device == NULL) return InputDeviceIdentifier();
262 return device->identifier;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263}
264
Jeff Brown90655042010-12-02 13:50:46 -0800265uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800266 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800267 Device* device = getDeviceLocked(deviceId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268 if (device == NULL) return 0;
269 return device->classes;
270}
271
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800272void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800273 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800274 Device* device = getDeviceLocked(deviceId);
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800275 if (device && device->configuration) {
276 *outConfiguration = *device->configuration;
Jeff Brown1f245102010-11-18 20:53:46 -0800277 } else {
278 outConfiguration->clear();
Jeff Brown47e6b1b2010-11-29 17:37:49 -0800279 }
280}
281
Jeff Brown6d0fec22010-07-23 21:28:06 -0700282status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
283 RawAbsoluteAxisInfo* outAxisInfo) const {
Jeff Brown8d608662010-08-30 03:02:23 -0700284 outAxisInfo->clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700285
Jeff Brownba421dd2011-08-10 15:07:05 -0700286 if (axis >= 0 && axis <= ABS_MAX) {
287 AutoMutex _l(mLock);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288
Jeff Brownba421dd2011-08-10 15:07:05 -0700289 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700290 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
Jeff Brownba421dd2011-08-10 15:07:05 -0700291 struct input_absinfo info;
292 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
Steve Block8564c8d2012-01-05 23:22:43 +0000293 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Jeff Brownba421dd2011-08-10 15:07:05 -0700294 axis, device->identifier.name.string(), device->fd, errno);
295 return -errno;
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297
Jeff Brownba421dd2011-08-10 15:07:05 -0700298 if (info.minimum != info.maximum) {
299 outAxisInfo->valid = true;
300 outAxisInfo->minValue = info.minimum;
301 outAxisInfo->maxValue = info.maximum;
302 outAxisInfo->flat = info.flat;
303 outAxisInfo->fuzz = info.fuzz;
304 outAxisInfo->resolution = info.resolution;
305 }
306 return OK;
307 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 }
Jeff Brownba421dd2011-08-10 15:07:05 -0700309 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310}
311
Jeff Browncc0c1592011-02-19 05:07:28 -0800312bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
313 if (axis >= 0 && axis <= REL_MAX) {
314 AutoMutex _l(mLock);
315
316 Device* device = getDeviceLocked(deviceId);
Jeff Brownba421dd2011-08-10 15:07:05 -0700317 if (device) {
Jeff Browncc0c1592011-02-19 05:07:28 -0800318 return test_bit(axis, device->relBitmask);
319 }
320 }
321 return false;
322}
323
Jeff Brown80fd47c2011-05-24 01:07:44 -0700324bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
325 if (property >= 0 && property <= INPUT_PROP_MAX) {
326 AutoMutex _l(mLock);
327
328 Device* device = getDeviceLocked(deviceId);
Jeff Brownba421dd2011-08-10 15:07:05 -0700329 if (device) {
Jeff Brown80fd47c2011-05-24 01:07:44 -0700330 return test_bit(property, device->propBitmask);
331 }
332 }
333 return false;
334}
335
Jeff Brown6d0fec22010-07-23 21:28:06 -0700336int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700337 if (scanCode >= 0 && scanCode <= KEY_MAX) {
338 AutoMutex _l(mLock);
339
Jeff Brown90655042010-12-02 13:50:46 -0800340 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700341 if (device && !device->isVirtual() && test_bit(scanCode, device->keyBitmask)) {
Jeff Brownba421dd2011-08-10 15:07:05 -0700342 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
343 memset(keyState, 0, sizeof(keyState));
344 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
345 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
346 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 }
348 }
Jeff Brownc5ed5912010-07-14 18:48:53 -0700349 return AKEY_STATE_UNKNOWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350}
351
Jeff Brown6d0fec22010-07-23 21:28:06 -0700352int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
353 AutoMutex _l(mLock);
Jeff Brown46b9ac02010-04-22 18:58:52 -0700354
Jeff Brown90655042010-12-02 13:50:46 -0800355 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700356 if (device && !device->isVirtual() && device->keyMap.haveKeyLayout()) {
Jeff Brownba421dd2011-08-10 15:07:05 -0700357 Vector<int32_t> scanCodes;
358 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
359 if (scanCodes.size() != 0) {
360 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
361 memset(keyState, 0, sizeof(keyState));
362 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
363 for (size_t i = 0; i < scanCodes.size(); i++) {
364 int32_t sc = scanCodes.itemAt(i);
365 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
366 return AKEY_STATE_DOWN;
367 }
368 }
369 return AKEY_STATE_UP;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 }
371 }
372 }
Jeff Brownc5ed5912010-07-14 18:48:53 -0700373 return AKEY_STATE_UNKNOWN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700374}
375
Jeff Brown6d0fec22010-07-23 21:28:06 -0700376int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Jeff Brown46b9ac02010-04-22 18:58:52 -0700377 if (sw >= 0 && sw <= SW_MAX) {
378 AutoMutex _l(mLock);
379
Jeff Brown90655042010-12-02 13:50:46 -0800380 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700381 if (device && !device->isVirtual() && test_bit(sw, device->swBitmask)) {
Jeff Brownba421dd2011-08-10 15:07:05 -0700382 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
383 memset(swState, 0, sizeof(swState));
384 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
385 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
386 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700387 }
Jeff Brown46b9ac02010-04-22 18:58:52 -0700388 }
Jeff Brownc5ed5912010-07-14 18:48:53 -0700389 return AKEY_STATE_UNKNOWN;
Jeff Brown46b9ac02010-04-22 18:58:52 -0700390}
391
Jeff Brown2717eff2011-06-30 23:53:07 -0700392status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
Jeff Brown06309752011-08-11 17:10:06 -0700393 *outValue = 0;
394
Jeff Brown2717eff2011-06-30 23:53:07 -0700395 if (axis >= 0 && axis <= ABS_MAX) {
396 AutoMutex _l(mLock);
397
398 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700399 if (device && !device->isVirtual() && test_bit(axis, device->absBitmask)) {
Jeff Brownba421dd2011-08-10 15:07:05 -0700400 struct input_absinfo info;
401 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
Steve Block8564c8d2012-01-05 23:22:43 +0000402 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Jeff Brownba421dd2011-08-10 15:07:05 -0700403 axis, device->identifier.name.string(), device->fd, errno);
404 return -errno;
405 }
406
407 *outValue = info.value;
408 return OK;
Jeff Brown2717eff2011-06-30 23:53:07 -0700409 }
410 }
Jeff Brown2717eff2011-06-30 23:53:07 -0700411 return -1;
412}
413
Jeff Brown6d0fec22010-07-23 21:28:06 -0700414bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
415 const int32_t* keyCodes, uint8_t* outFlags) const {
416 AutoMutex _l(mLock);
417
Jeff Brown90655042010-12-02 13:50:46 -0800418 Device* device = getDeviceLocked(deviceId);
Jeff Brownba421dd2011-08-10 15:07:05 -0700419 if (device && device->keyMap.haveKeyLayout()) {
420 Vector<int32_t> scanCodes;
421 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
422 scanCodes.clear();
Jeff Brown6d0fec22010-07-23 21:28:06 -0700423
Jeff Brownba421dd2011-08-10 15:07:05 -0700424 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
425 keyCodes[codeIndex], &scanCodes);
426 if (! err) {
427 // check the possible scan codes identified by the layout map against the
428 // map of codes actually emitted by the driver
429 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
430 if (test_bit(scanCodes[sc], device->keyBitmask)) {
431 outFlags[codeIndex] = 1;
432 break;
433 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700434 }
435 }
436 }
Jeff Brownba421dd2011-08-10 15:07:05 -0700437 return true;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700438 }
Jeff Brownba421dd2011-08-10 15:07:05 -0700439 return false;
Jeff Brown6d0fec22010-07-23 21:28:06 -0700440}
441
Jeff Brown49ccac52012-04-11 18:27:33 -0700442status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode,
443 int32_t* outKeycode, uint32_t* outFlags) const {
Dianne Hackborne3dd8842009-07-14 12:06:54 -0700444 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800445 Device* device = getDeviceLocked(deviceId);
Jeff Brown49ccac52012-04-11 18:27:33 -0700446
Jeff Brown4a3862f2012-04-17 18:50:05 -0700447 if (device) {
448 // Check the key character map first.
449 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
450 if (kcm != NULL) {
451 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
452 *outFlags = 0;
453 return NO_ERROR;
454 }
455 }
456
457 // Check the key layout next.
458 if (device->keyMap.haveKeyLayout()) {
459 if (!device->keyMap.keyLayoutMap->mapKey(
460 scanCode, usageCode, outKeycode, outFlags)) {
461 return NO_ERROR;
462 }
Dianne Hackborne3dd8842009-07-14 12:06:54 -0700463 }
464 }
Jeff Brown49ccac52012-04-11 18:27:33 -0700465
Dianne Hackborne3dd8842009-07-14 12:06:54 -0700466 *outKeycode = 0;
467 *outFlags = 0;
468 return NAME_NOT_FOUND;
469}
470
Jeff Brown49ccac52012-04-11 18:27:33 -0700471status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Jeff Brown6f2fba42011-02-19 01:08:02 -0800472 AutoMutex _l(mLock);
473 Device* device = getDeviceLocked(deviceId);
474
475 if (device && device->keyMap.haveKeyLayout()) {
Jeff Brown49ccac52012-04-11 18:27:33 -0700476 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
Jeff Brown6f2fba42011-02-19 01:08:02 -0800477 if (err == NO_ERROR) {
478 return NO_ERROR;
479 }
480 }
481
Jeff Brown6f2fba42011-02-19 01:08:02 -0800482 return NAME_NOT_FOUND;
483}
484
Jeff Brown1a84fd12011-06-02 01:26:32 -0700485void EventHub::setExcludedDevices(const Vector<String8>& devices) {
Jeff Brownf2f48712010-10-01 17:46:21 -0700486 AutoMutex _l(mLock);
487
Jeff Brown1a84fd12011-06-02 01:26:32 -0700488 mExcludedDevices = devices;
Mike Lockwood1d9dfc52009-07-16 11:11:18 -0400489}
490
Jeff Brown49754db2011-07-01 17:37:58 -0700491bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
492 AutoMutex _l(mLock);
493 Device* device = getDeviceLocked(deviceId);
494 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
495 if (test_bit(scanCode, device->keyBitmask)) {
496 return true;
497 }
498 }
499 return false;
500}
501
Jeff Brown497a92c2010-09-12 17:55:08 -0700502bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
503 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800504 Device* device = getDeviceLocked(deviceId);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700505 if (device && led >= 0 && led <= LED_MAX) {
506 if (test_bit(led, device->ledBitmask)) {
507 return true;
Jeff Brown497a92c2010-09-12 17:55:08 -0700508 }
509 }
510 return false;
511}
512
513void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
514 AutoMutex _l(mLock);
Jeff Brown90655042010-12-02 13:50:46 -0800515 Device* device = getDeviceLocked(deviceId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700516 if (device && !device->isVirtual() && led >= 0 && led <= LED_MAX) {
Jeff Brown497a92c2010-09-12 17:55:08 -0700517 struct input_event ev;
518 ev.time.tv_sec = 0;
519 ev.time.tv_usec = 0;
520 ev.type = EV_LED;
521 ev.code = led;
522 ev.value = on ? 1 : 0;
523
524 ssize_t nWrite;
525 do {
526 nWrite = write(device->fd, &ev, sizeof(struct input_event));
527 } while (nWrite == -1 && errno == EINTR);
528 }
529}
530
Jeff Brown90655042010-12-02 13:50:46 -0800531void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
532 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
533 outVirtualKeys.clear();
534
535 AutoMutex _l(mLock);
536 Device* device = getDeviceLocked(deviceId);
537 if (device && device->virtualKeyMap) {
538 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
539 }
540}
541
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700542sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Jeff Brown1e08fe92011-11-15 17:48:10 -0800543 AutoMutex _l(mLock);
544 Device* device = getDeviceLocked(deviceId);
545 if (device) {
Jeff Brown4a3862f2012-04-17 18:50:05 -0700546 return device->getKeyCharacterMap();
Jeff Brown1e08fe92011-11-15 17:48:10 -0800547 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700548 return NULL;
Jeff Brown1e08fe92011-11-15 17:48:10 -0800549}
550
Jeff Brown6ec6f792012-04-17 16:52:41 -0700551bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
552 const sp<KeyCharacterMap>& map) {
553 AutoMutex _l(mLock);
554 Device* device = getDeviceLocked(deviceId);
555 if (device) {
556 if (map != device->overlayKeyMap) {
557 device->overlayKeyMap = map;
558 device->combinedKeyMap = KeyCharacterMap::combine(
559 device->keyMap.keyCharacterMap, map);
560 return true;
561 }
562 }
563 return false;
564}
565
Jeff Browna47425a2012-04-13 04:09:27 -0700566void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
567 AutoMutex _l(mLock);
568 Device* device = getDeviceLocked(deviceId);
569 if (device && !device->isVirtual()) {
570 ff_effect effect;
571 memset(&effect, 0, sizeof(effect));
572 effect.type = FF_RUMBLE;
573 effect.id = device->ffEffectId;
574 effect.u.rumble.strong_magnitude = 0xc000;
575 effect.u.rumble.weak_magnitude = 0xc000;
576 effect.replay.length = (duration + 999999LL) / 1000000LL;
577 effect.replay.delay = 0;
578 if (ioctl(device->fd, EVIOCSFF, &effect)) {
579 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
580 device->identifier.name.string(), errno);
581 return;
582 }
583 device->ffEffectId = effect.id;
584
585 struct input_event ev;
586 ev.time.tv_sec = 0;
587 ev.time.tv_usec = 0;
588 ev.type = EV_FF;
589 ev.code = device->ffEffectId;
590 ev.value = 1;
591 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
592 ALOGW("Could not start force feedback effect on device %s due to error %d.",
593 device->identifier.name.string(), errno);
594 return;
595 }
596 device->ffEffectPlaying = true;
597 }
598}
599
600void EventHub::cancelVibrate(int32_t deviceId) {
601 AutoMutex _l(mLock);
602 Device* device = getDeviceLocked(deviceId);
603 if (device && !device->isVirtual()) {
604 if (device->ffEffectPlaying) {
605 device->ffEffectPlaying = false;
606
607 struct input_event ev;
608 ev.time.tv_sec = 0;
609 ev.time.tv_usec = 0;
610 ev.type = EV_FF;
611 ev.code = device->ffEffectId;
612 ev.value = 0;
613 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
614 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
615 device->identifier.name.string(), errno);
616 return;
617 }
618 }
619 }
620}
621
Jeff Brown90655042010-12-02 13:50:46 -0800622EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700623 if (deviceId == BUILT_IN_KEYBOARD_ID) {
Jeff Brown90655042010-12-02 13:50:46 -0800624 deviceId = mBuiltInKeyboardId;
625 }
Jeff Brown93fa9b32011-06-14 17:09:25 -0700626 ssize_t index = mDevices.indexOfKey(deviceId);
627 return index >= 0 ? mDevices.valueAt(index) : NULL;
628}
Jeff Brown90655042010-12-02 13:50:46 -0800629
Jeff Brown93fa9b32011-06-14 17:09:25 -0700630EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
631 for (size_t i = 0; i < mDevices.size(); i++) {
632 Device* device = mDevices.valueAt(i);
633 if (device->path == devicePath) {
Jeff Brown90655042010-12-02 13:50:46 -0800634 return device;
635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636 }
637 return NULL;
638}
639
Jeff Brownb7198742011-03-18 18:14:26 -0700640size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
Steve Blockec193de2012-01-09 18:35:44 +0000641 ALOG_ASSERT(bufferSize >= 1);
Mike Lockwood1d9dfc52009-07-16 11:11:18 -0400642
Jeff Brown93fa9b32011-06-14 17:09:25 -0700643 AutoMutex _l(mLock);
Mike Lockwood1d9dfc52009-07-16 11:11:18 -0400644
Jeff Brownb7198742011-03-18 18:14:26 -0700645 struct input_event readBuffer[bufferSize];
646
647 RawEvent* event = buffer;
648 size_t capacity = bufferSize;
Jeff Brown93fa9b32011-06-14 17:09:25 -0700649 bool awoken = false;
Jeff Browncc2e7172010-08-17 16:48:25 -0700650 for (;;) {
Jeff Brownb7198742011-03-18 18:14:26 -0700651 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
652
Jeff Brown1a84fd12011-06-02 01:26:32 -0700653 // Reopen input devices if needed.
Jeff Brown93fa9b32011-06-14 17:09:25 -0700654 if (mNeedToReopenDevices) {
655 mNeedToReopenDevices = false;
Jeff Brown1a84fd12011-06-02 01:26:32 -0700656
Steve Block6215d3f2012-01-04 20:05:49 +0000657 ALOGI("Reopening all input devices due to a configuration change.");
Jeff Brown1a84fd12011-06-02 01:26:32 -0700658
Jeff Brown93fa9b32011-06-14 17:09:25 -0700659 closeAllDevicesLocked();
Jeff Brown1a84fd12011-06-02 01:26:32 -0700660 mNeedToScanDevices = true;
661 break; // return to the caller before we actually rescan
662 }
663
Jeff Browncc2e7172010-08-17 16:48:25 -0700664 // Report any devices that had last been added/removed.
Jeff Brownb7198742011-03-18 18:14:26 -0700665 while (mClosingDevices) {
Jeff Brown90655042010-12-02 13:50:46 -0800666 Device* device = mClosingDevices;
Steve Block71f2cf12011-10-20 11:56:00 +0100667 ALOGV("Reporting device closed: id=%d, name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 device->id, device->path.string());
669 mClosingDevices = device->next;
Jeff Brownb7198742011-03-18 18:14:26 -0700670 event->when = now;
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700671 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
Jeff Brownb7198742011-03-18 18:14:26 -0700672 event->type = DEVICE_REMOVED;
673 event += 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 delete device;
Jeff Brown7342bb92010-10-01 18:55:43 -0700675 mNeedToSendFinishedDeviceScan = true;
Jeff Brownb7198742011-03-18 18:14:26 -0700676 if (--capacity == 0) {
677 break;
678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800679 }
Jeff Brown6d0fec22010-07-23 21:28:06 -0700680
Jeff Brown1a84fd12011-06-02 01:26:32 -0700681 if (mNeedToScanDevices) {
682 mNeedToScanDevices = false;
Jeff Brown93fa9b32011-06-14 17:09:25 -0700683 scanDevicesLocked();
Jeff Brown1a84fd12011-06-02 01:26:32 -0700684 mNeedToSendFinishedDeviceScan = true;
685 }
686
Jeff Brownb7198742011-03-18 18:14:26 -0700687 while (mOpeningDevices != NULL) {
Jeff Brown90655042010-12-02 13:50:46 -0800688 Device* device = mOpeningDevices;
Steve Block71f2cf12011-10-20 11:56:00 +0100689 ALOGV("Reporting device opened: id=%d, name=%s\n",
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 device->id, device->path.string());
691 mOpeningDevices = device->next;
Jeff Brownb7198742011-03-18 18:14:26 -0700692 event->when = now;
693 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
694 event->type = DEVICE_ADDED;
695 event += 1;
Jeff Brown7342bb92010-10-01 18:55:43 -0700696 mNeedToSendFinishedDeviceScan = true;
Jeff Brownb7198742011-03-18 18:14:26 -0700697 if (--capacity == 0) {
698 break;
699 }
Jeff Brown7342bb92010-10-01 18:55:43 -0700700 }
701
702 if (mNeedToSendFinishedDeviceScan) {
703 mNeedToSendFinishedDeviceScan = false;
Jeff Brownb7198742011-03-18 18:14:26 -0700704 event->when = now;
705 event->type = FINISHED_DEVICE_SCAN;
706 event += 1;
707 if (--capacity == 0) {
708 break;
709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 }
711
Jeff Browncc2e7172010-08-17 16:48:25 -0700712 // Grab the next input event.
Jeff Brown93fa9b32011-06-14 17:09:25 -0700713 bool deviceChanged = false;
714 while (mPendingEventIndex < mPendingEventCount) {
715 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
716 if (eventItem.data.u32 == EPOLL_ID_INOTIFY) {
717 if (eventItem.events & EPOLLIN) {
718 mPendingINotify = true;
719 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000720 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700721 }
722 continue;
723 }
724
725 if (eventItem.data.u32 == EPOLL_ID_WAKE) {
726 if (eventItem.events & EPOLLIN) {
Steve Block71f2cf12011-10-20 11:56:00 +0100727 ALOGV("awoken after wake()");
Jeff Brown93fa9b32011-06-14 17:09:25 -0700728 awoken = true;
729 char buffer[16];
730 ssize_t nRead;
731 do {
732 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
733 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
734 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000735 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Jeff Brown93fa9b32011-06-14 17:09:25 -0700736 eventItem.events);
737 }
738 continue;
739 }
740
741 ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
742 if (deviceIndex < 0) {
Steve Block8564c8d2012-01-05 23:22:43 +0000743 ALOGW("Received unexpected epoll event 0x%08x for unknown device id %d.",
Jeff Brown93fa9b32011-06-14 17:09:25 -0700744 eventItem.events, eventItem.data.u32);
745 continue;
746 }
747
748 Device* device = mDevices.valueAt(deviceIndex);
749 if (eventItem.events & EPOLLIN) {
750 int32_t readSize = read(device->fd, readBuffer,
751 sizeof(struct input_event) * capacity);
752 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
753 // Device was removed before INotify noticed.
Jeff Brown41305542011-10-05 11:14:13 -0700754 ALOGW("could not get event, removed? (fd: %d size: %d bufferSize: %d "
755 "capacity: %d errno: %d)\n",
756 device->fd, readSize, bufferSize, capacity, errno);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700757 deviceChanged = true;
758 closeDeviceLocked(device);
759 } else if (readSize < 0) {
Jeff Browncc2e7172010-08-17 16:48:25 -0700760 if (errno != EAGAIN && errno != EINTR) {
Steve Block8564c8d2012-01-05 23:22:43 +0000761 ALOGW("could not get event (errno=%d)", errno);
Jeff Browncc2e7172010-08-17 16:48:25 -0700762 }
763 } else if ((readSize % sizeof(struct input_event)) != 0) {
Steve Block3762c312012-01-06 19:20:56 +0000764 ALOGE("could not get event (wrong size: %d)", readSize);
Jeff Browncc2e7172010-08-17 16:48:25 -0700765 } else {
Jeff Brownb7198742011-03-18 18:14:26 -0700766 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
767
768 size_t count = size_t(readSize) / sizeof(struct input_event);
769 for (size_t i = 0; i < count; i++) {
Jeff Brown4dac9012013-04-10 01:03:19 -0700770 struct input_event& iev = readBuffer[i];
771 ALOGV("%s got: time=%d.%06d, type=%d, code=%d, value=%d",
JP Abgrall25a465b2012-05-16 10:33:49 -0700772 device->path.string(),
773 (int) iev.time.tv_sec, (int) iev.time.tv_usec,
774 iev.type, iev.code, iev.value);
775
Jeff Brown4dac9012013-04-10 01:03:19 -0700776 // Some input devices may have a better concept of the time
777 // when an input event was actually generated than the kernel
778 // which simply timestamps all events on entry to evdev.
779 // This is a custom Android extension of the input protocol
780 // mainly intended for use with uinput based device drivers.
781 if (iev.type == EV_MSC) {
782 if (iev.code == MSC_ANDROID_TIME_SEC) {
783 device->timestampOverrideSec = iev.value;
784 continue;
785 } else if (iev.code == MSC_ANDROID_TIME_USEC) {
786 device->timestampOverrideUsec = iev.value;
787 continue;
788 }
789 }
790 if (device->timestampOverrideSec || device->timestampOverrideUsec) {
791 iev.time.tv_sec = device->timestampOverrideSec;
792 iev.time.tv_usec = device->timestampOverrideUsec;
793 if (iev.type == EV_SYN && iev.code == SYN_REPORT) {
794 device->timestampOverrideSec = 0;
795 device->timestampOverrideUsec = 0;
796 }
797 ALOGV("applied override time %d.%06d",
798 int(iev.time.tv_sec), int(iev.time.tv_usec));
799 }
800
Jeff Brown4e91a182011-04-07 11:38:09 -0700801#ifdef HAVE_POSIX_CLOCKS
802 // Use the time specified in the event instead of the current time
803 // so that downstream code can get more accurate estimates of
804 // event dispatch latency from the time the event is enqueued onto
805 // the evdev client buffer.
806 //
807 // The event's timestamp fortuitously uses the same monotonic clock
808 // time base as the rest of Android. The kernel event device driver
809 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
810 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
811 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
812 // system call that also queries ktime_get_ts().
813 event->when = nsecs_t(iev.time.tv_sec) * 1000000000LL
814 + nsecs_t(iev.time.tv_usec) * 1000LL;
JP Abgrall25a465b2012-05-16 10:33:49 -0700815 ALOGV("event time %lld, now %lld", event->when, now);
Jeff Brownf33b2b22012-10-05 17:59:56 -0700816
817 // Bug 7291243: Add a guard in case the kernel generates timestamps
818 // that appear to be far into the future because they were generated
819 // using the wrong clock source.
820 //
821 // This can happen because when the input device is initially opened
822 // it has a default clock source of CLOCK_REALTIME. Any input events
823 // enqueued right after the device is opened will have timestamps
824 // generated using CLOCK_REALTIME. We later set the clock source
825 // to CLOCK_MONOTONIC but it is already too late.
826 //
827 // Invalid input event timestamps can result in ANRs, crashes and
828 // and other issues that are hard to track down. We must not let them
829 // propagate through the system.
830 //
831 // Log a warning so that we notice the problem and recover gracefully.
832 if (event->when >= now + 10 * 1000000000LL) {
833 // Double-check. Time may have moved on.
834 nsecs_t time = systemTime(SYSTEM_TIME_MONOTONIC);
835 if (event->when > time) {
836 ALOGW("An input event from %s has a timestamp that appears to "
837 "have been generated using the wrong clock source "
838 "(expected CLOCK_MONOTONIC): "
839 "event time %lld, current time %lld, call time %lld. "
840 "Using current time instead.",
841 device->path.string(), event->when, time, now);
842 event->when = time;
843 } else {
844 ALOGV("Event time is ok but failed the fast path and required "
845 "an extra call to systemTime: "
846 "event time %lld, current time %lld, call time %lld.",
847 event->when, time, now);
848 }
849 }
Jeff Brown4e91a182011-04-07 11:38:09 -0700850#else
Jeff Brownb7198742011-03-18 18:14:26 -0700851 event->when = now;
Jeff Brown4e91a182011-04-07 11:38:09 -0700852#endif
Jeff Brownb7198742011-03-18 18:14:26 -0700853 event->deviceId = deviceId;
854 event->type = iev.type;
Jeff Brown49ccac52012-04-11 18:27:33 -0700855 event->code = iev.code;
Jeff Brownb7198742011-03-18 18:14:26 -0700856 event->value = iev.value;
Jeff Brownb7198742011-03-18 18:14:26 -0700857 event += 1;
Jeff Brown4dac9012013-04-10 01:03:19 -0700858 capacity -= 1;
Jeff Brownb7198742011-03-18 18:14:26 -0700859 }
Jeff Brownb7198742011-03-18 18:14:26 -0700860 if (capacity == 0) {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700861 // The result buffer is full. Reset the pending event index
862 // so we will try to read the device again on the next iteration.
863 mPendingEventIndex -= 1;
Jeff Brownb7198742011-03-18 18:14:26 -0700864 break;
865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
Jeff Brownaf9e8d32012-04-12 17:32:48 -0700867 } else if (eventItem.events & EPOLLHUP) {
868 ALOGI("Removing device %s due to epoll hang-up event.",
869 device->identifier.name.string());
870 deviceChanged = true;
871 closeDeviceLocked(device);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700872 } else {
Steve Block8564c8d2012-01-05 23:22:43 +0000873 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Jeff Brown93fa9b32011-06-14 17:09:25 -0700874 eventItem.events, device->identifier.name.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
876 }
Jeff Browncc2e7172010-08-17 16:48:25 -0700877
Jeff Brown93fa9b32011-06-14 17:09:25 -0700878 // readNotify() will modify the list of devices so this must be done after
879 // processing all other events to ensure that we read all remaining events
880 // before closing the devices.
881 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
882 mPendingINotify = false;
883 readNotifyLocked();
884 deviceChanged = true;
Jeff Brown33bbfd22011-02-24 20:55:35 -0800885 }
886
Jeff Brown93fa9b32011-06-14 17:09:25 -0700887 // Report added or removed devices immediately.
888 if (deviceChanged) {
889 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
Jeff Browna9b84222010-10-14 02:23:43 -0700891
Jeff Brown93fa9b32011-06-14 17:09:25 -0700892 // Return now if we have collected any events or if we were explicitly awoken.
893 if (event != buffer || awoken) {
Jeff Brownb7198742011-03-18 18:14:26 -0700894 break;
895 }
896
Jeff Browncc2e7172010-08-17 16:48:25 -0700897 // Poll for events. Mind the wake lock dance!
Jeff Brown93fa9b32011-06-14 17:09:25 -0700898 // We hold a wake lock at all times except during epoll_wait(). This works due to some
Jeff Browncc2e7172010-08-17 16:48:25 -0700899 // subtle choreography. When a device driver has pending (unread) events, it acquires
900 // a kernel wake lock. However, once the last pending event has been read, the device
901 // driver will release the kernel wake lock. To prevent the system from going to sleep
902 // when this happens, the EventHub holds onto its own user wake lock while the client
903 // is processing events. Thus the system can only sleep if there are no events
904 // pending or currently being processed.
Jeff Brownaa3855d2011-03-17 01:34:19 -0700905 //
906 // The timeout is advisory only. If the device is asleep, it will not wake just to
907 // service the timeout.
Jeff Brown93fa9b32011-06-14 17:09:25 -0700908 mPendingEventIndex = 0;
909
910 mLock.unlock(); // release lock before poll, must be before release_wake_lock
Jeff Browncc2e7172010-08-17 16:48:25 -0700911 release_wake_lock(WAKE_LOCK_ID);
912
Jeff Brown93fa9b32011-06-14 17:09:25 -0700913 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
Jeff Browncc2e7172010-08-17 16:48:25 -0700914
915 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
Jeff Brown93fa9b32011-06-14 17:09:25 -0700916 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
Jeff Browncc2e7172010-08-17 16:48:25 -0700917
Jeff Brownaa3855d2011-03-17 01:34:19 -0700918 if (pollResult == 0) {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700919 // Timed out.
920 mPendingEventCount = 0;
921 break;
Jeff Brownaa3855d2011-03-17 01:34:19 -0700922 }
Jeff Brown93fa9b32011-06-14 17:09:25 -0700923
Jeff Brownaa3855d2011-03-17 01:34:19 -0700924 if (pollResult < 0) {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700925 // An error occurred.
926 mPendingEventCount = 0;
927
Jeff Brownb7198742011-03-18 18:14:26 -0700928 // Sleep after errors to avoid locking up the system.
929 // Hopefully the error is transient.
Jeff Browncc2e7172010-08-17 16:48:25 -0700930 if (errno != EINTR) {
Steve Block8564c8d2012-01-05 23:22:43 +0000931 ALOGW("poll failed (errno=%d)\n", errno);
Jeff Browncc2e7172010-08-17 16:48:25 -0700932 usleep(100000);
933 }
Jeff Brownb7198742011-03-18 18:14:26 -0700934 } else {
Jeff Brown93fa9b32011-06-14 17:09:25 -0700935 // Some events occurred.
936 mPendingEventCount = size_t(pollResult);
Jeff Browncc2e7172010-08-17 16:48:25 -0700937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800938 }
Jeff Brownb7198742011-03-18 18:14:26 -0700939
940 // All done, return the number of events we read.
941 return event - buffer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942}
943
Jeff Brown93fa9b32011-06-14 17:09:25 -0700944void EventHub::wake() {
Steve Block71f2cf12011-10-20 11:56:00 +0100945 ALOGV("wake() called");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946
Jeff Brown93fa9b32011-06-14 17:09:25 -0700947 ssize_t nWrite;
948 do {
949 nWrite = write(mWakeWritePipeFd, "W", 1);
950 } while (nWrite == -1 && errno == EINTR);
951
952 if (nWrite != 1 && errno != EAGAIN) {
Steve Block8564c8d2012-01-05 23:22:43 +0000953 ALOGW("Could not write wake signal, errno=%d", errno);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
Jeff Brown1a84fd12011-06-02 01:26:32 -0700955}
Jeff Brown90655042010-12-02 13:50:46 -0800956
Jeff Brown93fa9b32011-06-14 17:09:25 -0700957void EventHub::scanDevicesLocked() {
958 status_t res = scanDirLocked(DEVICE_PATH);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 if(res < 0) {
Steve Block3762c312012-01-06 19:20:56 +0000960 ALOGE("scan dir failed for %s\n", DEVICE_PATH);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 }
Jeff Brown9f25b7f2012-04-10 14:30:49 -0700962 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
963 createVirtualKeyboardLocked();
964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965}
966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967// ----------------------------------------------------------------------------
968
Jeff Brownfd035822010-06-30 16:10:35 -0700969static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
970 const uint8_t* end = array + endIndex;
971 array += startIndex;
972 while (array != end) {
973 if (*(array++) != 0) {
974 return true;
975 }
976 }
977 return false;
978}
979
980static const int32_t GAMEPAD_KEYCODES[] = {
981 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
982 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
983 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
984 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
985 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
Jeff Browncb1404e2011-01-15 18:14:15 -0800986 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
987 AKEYCODE_BUTTON_1, AKEYCODE_BUTTON_2, AKEYCODE_BUTTON_3, AKEYCODE_BUTTON_4,
988 AKEYCODE_BUTTON_5, AKEYCODE_BUTTON_6, AKEYCODE_BUTTON_7, AKEYCODE_BUTTON_8,
989 AKEYCODE_BUTTON_9, AKEYCODE_BUTTON_10, AKEYCODE_BUTTON_11, AKEYCODE_BUTTON_12,
990 AKEYCODE_BUTTON_13, AKEYCODE_BUTTON_14, AKEYCODE_BUTTON_15, AKEYCODE_BUTTON_16,
Jeff Brownfd035822010-06-30 16:10:35 -0700991};
992
Jeff Brown93fa9b32011-06-14 17:09:25 -0700993status_t EventHub::openDeviceLocked(const char *devicePath) {
Jeff Brown90655042010-12-02 13:50:46 -0800994 char buffer[80];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995
Steve Block71f2cf12011-10-20 11:56:00 +0100996 ALOGV("Opening device: %s", devicePath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
Jeff Brown874c1e92012-01-19 14:32:47 -0800998 int fd = open(devicePath, O_RDWR | O_CLOEXEC);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 if(fd < 0) {
Steve Block3762c312012-01-06 19:20:56 +00001000 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 return -1;
1002 }
1003
Jeff Brown90655042010-12-02 13:50:46 -08001004 InputDeviceIdentifier identifier;
1005
1006 // Get device name.
1007 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
1008 //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
1009 } else {
1010 buffer[sizeof(buffer) - 1] = '\0';
1011 identifier.name.setTo(buffer);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 }
Mike Lockwood15431a92009-07-17 00:10:10 -04001013
Jeff Brown90655042010-12-02 13:50:46 -08001014 // Check to see if the device is on our excluded list
Jeff Brown1a84fd12011-06-02 01:26:32 -07001015 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
1016 const String8& item = mExcludedDevices.itemAt(i);
1017 if (identifier.name == item) {
Steve Block6215d3f2012-01-04 20:05:49 +00001018 ALOGI("ignoring event id %s driver %s\n", devicePath, item.string());
Mike Lockwood15431a92009-07-17 00:10:10 -04001019 close(fd);
Mike Lockwood15431a92009-07-17 00:10:10 -04001020 return -1;
1021 }
1022 }
1023
Jeff Brown90655042010-12-02 13:50:46 -08001024 // Get device driver version.
1025 int driverVersion;
1026 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Steve Block3762c312012-01-06 19:20:56 +00001027 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
Jeff Brown90655042010-12-02 13:50:46 -08001028 close(fd);
1029 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
1031
Jeff Brown90655042010-12-02 13:50:46 -08001032 // Get device identifier.
1033 struct input_id inputId;
1034 if(ioctl(fd, EVIOCGID, &inputId)) {
Steve Block3762c312012-01-06 19:20:56 +00001035 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
Jeff Brown90655042010-12-02 13:50:46 -08001036 close(fd);
1037 return -1;
1038 }
1039 identifier.bus = inputId.bustype;
1040 identifier.product = inputId.product;
1041 identifier.vendor = inputId.vendor;
1042 identifier.version = inputId.version;
1043
1044 // Get device physical location.
1045 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1046 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1047 } else {
1048 buffer[sizeof(buffer) - 1] = '\0';
1049 identifier.location.setTo(buffer);
1050 }
1051
1052 // Get device unique id.
1053 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1054 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1055 } else {
1056 buffer[sizeof(buffer) - 1] = '\0';
1057 identifier.uniqueId.setTo(buffer);
1058 }
1059
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001060 // Fill in the descriptor.
1061 setDescriptor(identifier);
Jeff Browne38fdfa2012-04-06 14:51:01 -07001062
Jeff Brown90655042010-12-02 13:50:46 -08001063 // Make file descriptor non-blocking for use with poll().
Jeff Browncc2e7172010-08-17 16:48:25 -07001064 if (fcntl(fd, F_SETFL, O_NONBLOCK)) {
Steve Block3762c312012-01-06 19:20:56 +00001065 ALOGE("Error %d making device file descriptor non-blocking.", errno);
Jeff Browncc2e7172010-08-17 16:48:25 -07001066 close(fd);
1067 return -1;
1068 }
1069
Jeff Brown90655042010-12-02 13:50:46 -08001070 // Allocate device. (The device object takes ownership of the fd at this point.)
1071 int32_t deviceId = mNextDeviceId++;
1072 Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073
Jeff Browne38fdfa2012-04-06 14:51:01 -07001074 ALOGV("add device %d: %s\n", deviceId, devicePath);
1075 ALOGV(" bus: %04x\n"
1076 " vendor %04x\n"
1077 " product %04x\n"
1078 " version %04x\n",
Jeff Brown90655042010-12-02 13:50:46 -08001079 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Jeff Browne38fdfa2012-04-06 14:51:01 -07001080 ALOGV(" name: \"%s\"\n", identifier.name.string());
1081 ALOGV(" location: \"%s\"\n", identifier.location.string());
1082 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.string());
Jeff Brown49ccac52012-04-11 18:27:33 -07001083 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.string());
Jeff Browne38fdfa2012-04-06 14:51:01 -07001084 ALOGV(" driver: v%d.%d.%d\n",
Jeff Brown90655042010-12-02 13:50:46 -08001085 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001087 // Load the configuration file for the device.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001088 loadConfigurationLocked(device);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001089
Jeff Brownfd035822010-06-30 16:10:35 -07001090 // Figure out the kinds of events the device reports.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001091 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1092 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1093 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1094 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1095 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
Jeff Browna47425a2012-04-13 04:09:27 -07001096 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
Jeff Brown93fa9b32011-06-14 17:09:25 -07001097 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
Jeff Browncc0c1592011-02-19 05:07:28 -08001098
Jeff Brown6f2fba42011-02-19 01:08:02 -08001099 // See if this is a keyboard. Ignore everything in the button range except for
1100 // joystick and gamepad buttons which are handled like keyboards for the most part.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001101 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1102 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
Jeff Brown6f2fba42011-02-19 01:08:02 -08001103 sizeof_bit_array(KEY_MAX + 1));
Jeff Brown93fa9b32011-06-14 17:09:25 -07001104 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001105 sizeof_bit_array(BTN_MOUSE))
Jeff Brown93fa9b32011-06-14 17:09:25 -07001106 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001107 sizeof_bit_array(BTN_DIGI));
Jeff Brown6f2fba42011-02-19 01:08:02 -08001108 if (haveKeyboardKeys || haveGamepadButtons) {
1109 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001111
Jeff Brown83c09682010-12-23 17:50:18 -08001112 // See if this is a cursor device such as a trackball or mouse.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001113 if (test_bit(BTN_MOUSE, device->keyBitmask)
1114 && test_bit(REL_X, device->relBitmask)
1115 && test_bit(REL_Y, device->relBitmask)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08001116 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
Jeff Brownfd035822010-06-30 16:10:35 -07001118
1119 // See if this is a touch pad.
Jeff Brown6f2fba42011-02-19 01:08:02 -08001120 // Is this a new modern multi-touch driver?
Jeff Brown93fa9b32011-06-14 17:09:25 -07001121 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1122 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08001123 // Some joysticks such as the PS3 controller report axes that conflict
1124 // with the ABS_MT range. Try to confirm that the device really is
1125 // a touch screen.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001126 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
Jeff Brown58a2da82011-01-25 16:02:22 -08001127 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
Jeff Brownfd035822010-06-30 16:10:35 -07001128 }
Jeff Brown6f2fba42011-02-19 01:08:02 -08001129 // Is this an old style single-touch driver?
Jeff Brown93fa9b32011-06-14 17:09:25 -07001130 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1131 && test_bit(ABS_X, device->absBitmask)
1132 && test_bit(ABS_Y, device->absBitmask)) {
Jeff Brown6f2fba42011-02-19 01:08:02 -08001133 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001136 // See if this device is a joystick.
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001137 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1138 // from other devices such as accelerometers that also have absolute axes.
Jeff Brown9ee285a2011-08-31 12:56:34 -07001139 if (haveGamepadButtons) {
1140 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1141 for (int i = 0; i <= ABS_MAX; i++) {
1142 if (test_bit(i, device->absBitmask)
1143 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1144 device->classes = assumedClasses;
1145 break;
1146 }
1147 }
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001148 }
1149
Jeff Brown93fa9b32011-06-14 17:09:25 -07001150 // Check whether this device has switches.
1151 for (int i = 0; i <= SW_MAX; i++) {
1152 if (test_bit(i, device->swBitmask)) {
1153 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1154 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157
Jeff Browna47425a2012-04-13 04:09:27 -07001158 // Check whether this device supports the vibrator.
1159 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1160 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1161 }
1162
Jeff Brown93fa9b32011-06-14 17:09:25 -07001163 // Configure virtual keys.
Jeff Brown58a2da82011-01-25 16:02:22 -08001164 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
Jeff Brown90655042010-12-02 13:50:46 -08001165 // Load the virtual keys for the touch screen, if any.
1166 // We do this now so that we can make sure to load the keymap if necessary.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001167 status_t status = loadVirtualKeyMapLocked(device);
Jeff Brown90655042010-12-02 13:50:46 -08001168 if (!status) {
1169 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
Jeff Brown90655042010-12-02 13:50:46 -08001171 }
1172
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001173 // Load the key map.
1174 // We need to do this for joysticks too because the key layout may specify axes.
1175 status_t keyMapStatus = NAME_NOT_FOUND;
1176 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
Jeff Brown90655042010-12-02 13:50:46 -08001177 // Load the keymap for the device.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001178 keyMapStatus = loadKeyMapLocked(device);
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001179 }
Jeff Brown90655042010-12-02 13:50:46 -08001180
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001181 // Configure the keyboard, gamepad or virtual keyboard.
1182 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
Jeff Brown90655042010-12-02 13:50:46 -08001183 // Register the keyboard as a built-in keyboard if it is eligible.
Jeff Brown9e8e40c2011-03-03 03:39:29 -08001184 if (!keyMapStatus
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001185 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
Jeff Brown90655042010-12-02 13:50:46 -08001186 && isEligibleBuiltInKeyboard(device->identifier,
1187 device->configuration, &device->keyMap)) {
1188 mBuiltInKeyboardId = device->id;
Jeff Brown497a92c2010-09-12 17:55:08 -07001189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190
Ken Wakasa02a44f72013-07-05 04:08:36 +00001191 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1192 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1193 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1194 }
1195
Jeff Brownfd035822010-06-30 16:10:35 -07001196 // See if this device has a DPAD.
Jeff Brownf2f48712010-10-01 17:46:21 -07001197 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1198 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1199 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1200 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1201 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
Jeff Brown46b9ac02010-04-22 18:58:52 -07001202 device->classes |= INPUT_DEVICE_CLASS_DPAD;
Dianne Hackborn0dd7cb42009-08-04 05:49:43 -07001203 }
Jeff Brown497a92c2010-09-12 17:55:08 -07001204
Jeff Brownfd035822010-06-30 16:10:35 -07001205 // See if this device has a gamepad.
Kenny Root1d79a9d2010-10-21 15:46:03 -07001206 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
Jeff Brownf2f48712010-10-01 17:46:21 -07001207 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
Jeff Brownfd035822010-06-30 16:10:35 -07001208 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1209 break;
1210 }
1211 }
Michael Wrighta0a72852013-02-21 23:51:45 -08001212
1213 // Disable kernel key repeat since we handle it ourselves
1214 unsigned int repeatRate[] = {0,0};
1215 if (ioctl(fd, EVIOCSREP, repeatRate)) {
1216 ALOGW("Unable to disable kernel key repeat for %s: %s", devicePath, strerror(errno));
1217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219
Sean McNeilaeb00c42010-06-23 16:00:37 +07001220 // If the device isn't recognized as something we handle, don't monitor it.
1221 if (device->classes == 0) {
Steve Block71f2cf12011-10-20 11:56:00 +01001222 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Jeff Brown90655042010-12-02 13:50:46 -08001223 deviceId, devicePath, device->identifier.name.string());
Sean McNeilaeb00c42010-06-23 16:00:37 +07001224 delete device;
1225 return -1;
1226 }
1227
Jeff Brown56194eb2011-03-02 19:23:13 -08001228 // Determine whether the device is external or internal.
Jeff Brown93fa9b32011-06-14 17:09:25 -07001229 if (isExternalDeviceLocked(device)) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001230 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1231 }
1232
Jeff Brown93fa9b32011-06-14 17:09:25 -07001233 // Register with epoll.
1234 struct epoll_event eventItem;
1235 memset(&eventItem, 0, sizeof(eventItem));
1236 eventItem.events = EPOLLIN;
1237 eventItem.data.u32 = deviceId;
1238 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
Steve Block3762c312012-01-06 19:20:56 +00001239 ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
Jeff Brown93fa9b32011-06-14 17:09:25 -07001240 delete device;
1241 return -1;
1242 }
1243
Jeff Browne22afbe2011-12-16 13:45:40 -08001244 // Enable wake-lock behavior on kernels that support it.
1245 // TODO: Only need this for devices that can really wake the system.
Jeff Browneca3cf52012-04-06 19:31:36 -07001246 bool usingSuspendBlockIoctl = !ioctl(fd, EVIOCSSUSPENDBLOCK, 1);
1247
1248 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1249 // associated with input events. This is important because the input system
1250 // uses the timestamps extensively and assumes they were recorded using the monotonic
1251 // clock.
1252 //
1253 // In older kernel, before Linux 3.4, there was no way to tell the kernel which
1254 // clock to use to input event timestamps. The standard kernel behavior was to
1255 // record a real time timestamp, which isn't what we want. Android kernels therefore
1256 // contained a patch to the evdev_event() function in drivers/input/evdev.c to
1257 // replace the call to do_gettimeofday() with ktime_get_ts() to cause the monotonic
1258 // clock to be used instead of the real time clock.
1259 //
1260 // As of Linux 3.4, there is a new EVIOCSCLOCKID ioctl to set the desired clock.
1261 // Therefore, we no longer require the Android-specific kernel patch described above
1262 // as long as we make sure to set select the monotonic clock. We do that here.
Jeff Browna75fe052012-05-01 18:41:26 -07001263 int clockId = CLOCK_MONOTONIC;
1264 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
Jeff Browne22afbe2011-12-16 13:45:40 -08001265
Steve Block6215d3f2012-01-04 20:05:49 +00001266 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
Jeff Browne22afbe2011-12-16 13:45:40 -08001267 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, "
Jeff Browneca3cf52012-04-06 19:31:36 -07001268 "usingSuspendBlockIoctl=%s, usingClockIoctl=%s",
Jeff Brown90655042010-12-02 13:50:46 -08001269 deviceId, fd, devicePath, device->identifier.name.string(),
1270 device->classes,
1271 device->configurationFile.string(),
1272 device->keyMap.keyLayoutFile.string(),
1273 device->keyMap.keyCharacterMapFile.string(),
Jeff Browne22afbe2011-12-16 13:45:40 -08001274 toString(mBuiltInKeyboardId == deviceId),
Jeff Browneca3cf52012-04-06 19:31:36 -07001275 toString(usingSuspendBlockIoctl), toString(usingClockIoctl));
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001276
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001277 addDeviceLocked(device);
1278 return 0;
1279}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001281void EventHub::createVirtualKeyboardLocked() {
1282 InputDeviceIdentifier identifier;
1283 identifier.name = "Virtual";
1284 identifier.uniqueId = "<virtual>";
1285 setDescriptor(identifier);
1286
1287 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, String8("<virtual>"), identifier);
1288 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1289 | INPUT_DEVICE_CLASS_ALPHAKEY
1290 | INPUT_DEVICE_CLASS_DPAD
1291 | INPUT_DEVICE_CLASS_VIRTUAL;
1292 loadKeyMapLocked(device);
1293 addDeviceLocked(device);
1294}
1295
1296void EventHub::addDeviceLocked(Device* device) {
1297 mDevices.add(device->id, device);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 device->next = mOpeningDevices;
1299 mOpeningDevices = device;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300}
1301
Jeff Brown93fa9b32011-06-14 17:09:25 -07001302void EventHub::loadConfigurationLocked(Device* device) {
Jeff Brown90655042010-12-02 13:50:46 -08001303 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1304 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001305 if (device->configurationFile.isEmpty()) {
Steve Block5baa3a62011-12-20 16:23:08 +00001306 ALOGD("No input device configuration file found for device '%s'.",
Jeff Brown90655042010-12-02 13:50:46 -08001307 device->identifier.name.string());
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001308 } else {
1309 status_t status = PropertyMap::load(device->configurationFile,
1310 &device->configuration);
1311 if (status) {
Steve Block3762c312012-01-06 19:20:56 +00001312 ALOGE("Error loading input device configuration file for device '%s'. "
Jeff Brown90655042010-12-02 13:50:46 -08001313 "Using default configuration.",
1314 device->identifier.name.string());
Jeff Brown47e6b1b2010-11-29 17:37:49 -08001315 }
1316 }
1317}
1318
Jeff Brown93fa9b32011-06-14 17:09:25 -07001319status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
Jeff Brown90655042010-12-02 13:50:46 -08001320 // The virtual key map is supplied by the kernel as a system board property file.
1321 String8 path;
1322 path.append("/sys/board_properties/virtualkeys.");
1323 path.append(device->identifier.name);
1324 if (access(path.string(), R_OK)) {
1325 return NAME_NOT_FOUND;
1326 }
1327 return VirtualKeyMap::load(path, &device->virtualKeyMap);
Jeff Brown497a92c2010-09-12 17:55:08 -07001328}
1329
Jeff Brown93fa9b32011-06-14 17:09:25 -07001330status_t EventHub::loadKeyMapLocked(Device* device) {
Jeff Brown90655042010-12-02 13:50:46 -08001331 return device->keyMap.load(device->identifier, device->configuration);
Jeff Brown497a92c2010-09-12 17:55:08 -07001332}
1333
Jeff Brown93fa9b32011-06-14 17:09:25 -07001334bool EventHub::isExternalDeviceLocked(Device* device) {
Jeff Brown56194eb2011-03-02 19:23:13 -08001335 if (device->configuration) {
1336 bool value;
Max Braune81056f2011-08-30 14:35:45 -07001337 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1338 return !value;
Jeff Brown56194eb2011-03-02 19:23:13 -08001339 }
1340 }
1341 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1342}
1343
Jeff Brown90655042010-12-02 13:50:46 -08001344bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
1345 if (!device->keyMap.haveKeyLayout() || !device->keyBitmask) {
Dianne Hackborn0dd7cb42009-08-04 05:49:43 -07001346 return false;
1347 }
1348
1349 Vector<int32_t> scanCodes;
Jeff Brown6f2fba42011-02-19 01:08:02 -08001350 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
Dianne Hackborn0dd7cb42009-08-04 05:49:43 -07001351 const size_t N = scanCodes.size();
1352 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1353 int32_t sc = scanCodes.itemAt(i);
1354 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1355 return true;
1356 }
1357 }
1358
1359 return false;
1360}
1361
Jeff Brown93fa9b32011-06-14 17:09:25 -07001362status_t EventHub::closeDeviceByPathLocked(const char *devicePath) {
1363 Device* device = getDeviceByPathLocked(devicePath);
1364 if (device) {
1365 closeDeviceLocked(device);
1366 return 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
Steve Block71f2cf12011-10-20 11:56:00 +01001368 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 return -1;
1370}
1371
Jeff Brown93fa9b32011-06-14 17:09:25 -07001372void EventHub::closeAllDevicesLocked() {
1373 while (mDevices.size() > 0) {
1374 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1375 }
1376}
1377
1378void EventHub::closeDeviceLocked(Device* device) {
Steve Block6215d3f2012-01-04 20:05:49 +00001379 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x\n",
Jeff Brown33bbfd22011-02-24 20:55:35 -08001380 device->path.string(), device->identifier.name.string(), device->id,
1381 device->fd, device->classes);
1382
Jeff Brown33bbfd22011-02-24 20:55:35 -08001383 if (device->id == mBuiltInKeyboardId) {
Steve Block8564c8d2012-01-05 23:22:43 +00001384 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Jeff Brown33bbfd22011-02-24 20:55:35 -08001385 device->path.string(), mBuiltInKeyboardId);
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001386 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
Jeff Brown33bbfd22011-02-24 20:55:35 -08001387 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001388
Jeff Brown9f25b7f2012-04-10 14:30:49 -07001389 if (!device->isVirtual()) {
1390 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, NULL)) {
1391 ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
1392 }
Jeff Brown93fa9b32011-06-14 17:09:25 -07001393 }
1394
1395 mDevices.removeItem(device->id);
Jeff Brown33bbfd22011-02-24 20:55:35 -08001396 device->close();
1397
Jeff Brown8e9d4432011-03-12 19:46:59 -08001398 // Unlink for opening devices list if it is present.
1399 Device* pred = NULL;
1400 bool found = false;
1401 for (Device* entry = mOpeningDevices; entry != NULL; ) {
1402 if (entry == device) {
1403 found = true;
1404 break;
1405 }
1406 pred = entry;
1407 entry = entry->next;
1408 }
1409 if (found) {
1410 // Unlink the device from the opening devices list then delete it.
1411 // We don't need to tell the client that the device was closed because
1412 // it does not even know it was opened in the first place.
Steve Block6215d3f2012-01-04 20:05:49 +00001413 ALOGI("Device %s was immediately closed after opening.", device->path.string());
Jeff Brown8e9d4432011-03-12 19:46:59 -08001414 if (pred) {
1415 pred->next = device->next;
1416 } else {
1417 mOpeningDevices = device->next;
1418 }
1419 delete device;
1420 } else {
1421 // Link into closing devices list.
1422 // The device will be deleted later after we have informed the client.
1423 device->next = mClosingDevices;
1424 mClosingDevices = device;
1425 }
Jeff Brown33bbfd22011-02-24 20:55:35 -08001426}
1427
Jeff Brown93fa9b32011-06-14 17:09:25 -07001428status_t EventHub::readNotifyLocked() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 int res;
1430 char devname[PATH_MAX];
1431 char *filename;
1432 char event_buf[512];
1433 int event_size;
1434 int event_pos = 0;
1435 struct inotify_event *event;
1436
Steve Block71f2cf12011-10-20 11:56:00 +01001437 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Jeff Brown93fa9b32011-06-14 17:09:25 -07001438 res = read(mINotifyFd, event_buf, sizeof(event_buf));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 if(res < (int)sizeof(*event)) {
1440 if(errno == EINTR)
1441 return 0;
Steve Block8564c8d2012-01-05 23:22:43 +00001442 ALOGW("could not get event, %s\n", strerror(errno));
Jeff Brown93fa9b32011-06-14 17:09:25 -07001443 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
1445 //printf("got %d bytes of event information\n", res);
1446
Jeff Brown90655042010-12-02 13:50:46 -08001447 strcpy(devname, DEVICE_PATH);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 filename = devname + strlen(devname);
1449 *filename++ = '/';
1450
1451 while(res >= (int)sizeof(*event)) {
1452 event = (struct inotify_event *)(event_buf + event_pos);
1453 //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
1454 if(event->len) {
1455 strcpy(filename, event->name);
1456 if(event->mask & IN_CREATE) {
Jeff Brown93fa9b32011-06-14 17:09:25 -07001457 openDeviceLocked(devname);
1458 } else {
Steve Block6215d3f2012-01-04 20:05:49 +00001459 ALOGI("Removing device '%s' due to inotify event\n", devname);
Jeff Brown93fa9b32011-06-14 17:09:25 -07001460 closeDeviceByPathLocked(devname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
1462 }
1463 event_size = sizeof(*event) + event->len;
1464 res -= event_size;
1465 event_pos += event_size;
1466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 return 0;
1468}
1469
Jeff Brown93fa9b32011-06-14 17:09:25 -07001470status_t EventHub::scanDirLocked(const char *dirname)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471{
1472 char devname[PATH_MAX];
1473 char *filename;
1474 DIR *dir;
1475 struct dirent *de;
1476 dir = opendir(dirname);
1477 if(dir == NULL)
1478 return -1;
1479 strcpy(devname, dirname);
1480 filename = devname + strlen(devname);
1481 *filename++ = '/';
1482 while((de = readdir(dir))) {
1483 if(de->d_name[0] == '.' &&
1484 (de->d_name[1] == '\0' ||
1485 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1486 continue;
1487 strcpy(filename, de->d_name);
Jeff Brown93fa9b32011-06-14 17:09:25 -07001488 openDeviceLocked(devname);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 closedir(dir);
1491 return 0;
1492}
1493
Jeff Brown93fa9b32011-06-14 17:09:25 -07001494void EventHub::requestReopenDevices() {
Steve Block71f2cf12011-10-20 11:56:00 +01001495 ALOGV("requestReopenDevices() called");
Jeff Brown93fa9b32011-06-14 17:09:25 -07001496
1497 AutoMutex _l(mLock);
1498 mNeedToReopenDevices = true;
Jeff Brown1a84fd12011-06-02 01:26:32 -07001499}
1500
Jeff Brownf2f48712010-10-01 17:46:21 -07001501void EventHub::dump(String8& dump) {
1502 dump.append("Event Hub State:\n");
1503
1504 { // acquire lock
1505 AutoMutex _l(mLock);
1506
Jeff Brown90655042010-12-02 13:50:46 -08001507 dump.appendFormat(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Jeff Brownf2f48712010-10-01 17:46:21 -07001508
1509 dump.append(INDENT "Devices:\n");
1510
Jeff Brown93fa9b32011-06-14 17:09:25 -07001511 for (size_t i = 0; i < mDevices.size(); i++) {
1512 const Device* device = mDevices.valueAt(i);
1513 if (mBuiltInKeyboardId == device->id) {
1514 dump.appendFormat(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
1515 device->id, device->identifier.name.string());
1516 } else {
1517 dump.appendFormat(INDENT2 "%d: %s\n", device->id,
1518 device->identifier.name.string());
Jeff Brownf2f48712010-10-01 17:46:21 -07001519 }
Jeff Brown93fa9b32011-06-14 17:09:25 -07001520 dump.appendFormat(INDENT3 "Classes: 0x%08x\n", device->classes);
1521 dump.appendFormat(INDENT3 "Path: %s\n", device->path.string());
Jeff Browne38fdfa2012-04-06 14:51:01 -07001522 dump.appendFormat(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.string());
Jeff Brown93fa9b32011-06-14 17:09:25 -07001523 dump.appendFormat(INDENT3 "Location: %s\n", device->identifier.location.string());
1524 dump.appendFormat(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.string());
1525 dump.appendFormat(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
1526 "product=0x%04x, version=0x%04x\n",
1527 device->identifier.bus, device->identifier.vendor,
1528 device->identifier.product, device->identifier.version);
1529 dump.appendFormat(INDENT3 "KeyLayoutFile: %s\n",
1530 device->keyMap.keyLayoutFile.string());
1531 dump.appendFormat(INDENT3 "KeyCharacterMapFile: %s\n",
1532 device->keyMap.keyCharacterMapFile.string());
1533 dump.appendFormat(INDENT3 "ConfigurationFile: %s\n",
1534 device->configurationFile.string());
Jeff Brown61c08242012-04-19 11:14:33 -07001535 dump.appendFormat(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
1536 toString(device->overlayKeyMap != NULL));
Jeff Brownf2f48712010-10-01 17:46:21 -07001537 }
1538 } // release lock
1539}
1540
Jeff Brown89ef0722011-08-10 16:25:21 -07001541void EventHub::monitor() {
1542 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1543 mLock.lock();
1544 mLock.unlock();
1545}
1546
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548}; // namespace android