blob: 18c3ded8805aff7fcead70b21c5dba303091b2b2 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -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
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
22#include <memory.h>
23#include <stdint.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
27#include <sys/epoll.h>
28#include <sys/limits.h>
29#include <sys/inotify.h>
30#include <sys/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070031#include <sys/utsname.h>
32#include <unistd.h>
33
Michael Wrightd02c5b62014-02-10 15:10:22 -080034#define LOG_TAG "EventHub"
35
36// #define LOG_NDEBUG 0
37
38#include "EventHub.h"
39
40#include <hardware_legacy/power.h>
41
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080042#include <android-base/stringprintf.h>
Dan Albert677d87e2014-06-16 17:31:28 -070043#include <openssl/sha.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080044#include <utils/Log.h>
45#include <utils/Timers.h>
46#include <utils/threads.h>
47#include <utils/Errors.h>
48
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <input/KeyLayoutMap.h>
50#include <input/KeyCharacterMap.h>
51#include <input/VirtualKeyMap.h>
52
Michael Wrightd02c5b62014-02-10 15:10:22 -080053/* 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 */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070058#define test_bit(bit, array) ((array)[(bit)/8] & (1<<((bit)%8)))
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
60/* this macro computes the number of bytes needed to represent a bit array of the specified size */
Chih-Hung Hsieh4a186d42016-05-20 11:33:26 -070061#define sizeof_bit_array(bits) (((bits) + 7) / 8)
Michael Wrightd02c5b62014-02-10 15:10:22 -080062
63#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Siarhei Vishniakou25920312018-12-12 15:24:44 -080071static constexpr bool DEBUG = false;
72
Michael Wrightd02c5b62014-02-10 15:10:22 -080073static const char *WAKE_LOCK_ID = "KeyEvents";
74static const char *DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080075// v4l2 devices go directly into /dev
76static const char *VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080077
Michael Wrightd02c5b62014-02-10 15:10:22 -080078static inline const char* toString(bool value) {
79 return value ? "true" : "false";
80}
81
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010082static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -070083 SHA_CTX ctx;
84 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010085 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -070086 u_char digest[SHA_DIGEST_LENGTH];
87 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -080088
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010089 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -070090 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +010091 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -080092 }
93 return out;
94}
95
96static void getLinuxRelease(int* major, int* minor) {
97 struct utsname info;
98 if (uname(&info) || sscanf(info.release, "%d.%d", major, minor) <= 0) {
99 *major = 0, *minor = 0;
100 ALOGE("Could not get linux version: %s", strerror(errno));
101 }
102}
103
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800104/**
105 * Return true if name matches "v4l-touch*"
106 */
107static bool isV4lTouchNode(const char* name) {
108 return strstr(name, "v4l-touch") == name;
109}
110
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800111static nsecs_t processEventTimestamp(const struct input_event& event) {
112 // Use the time specified in the event instead of the current time
113 // so that downstream code can get more accurate estimates of
114 // event dispatch latency from the time the event is enqueued onto
115 // the evdev client buffer.
116 //
117 // The event's timestamp fortuitously uses the same monotonic clock
118 // time base as the rest of Android. The kernel event device driver
119 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
120 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
121 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
122 // system call that also queries ktime_get_ts().
123
124 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
125 microseconds_to_nanoseconds(event.time.tv_usec);
126 return inputEventTime;
127}
128
Michael Wrightd02c5b62014-02-10 15:10:22 -0800129// --- Global Functions ---
130
131uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
132 // Touch devices get dibs on touch-related axes.
133 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
134 switch (axis) {
135 case ABS_X:
136 case ABS_Y:
137 case ABS_PRESSURE:
138 case ABS_TOOL_WIDTH:
139 case ABS_DISTANCE:
140 case ABS_TILT_X:
141 case ABS_TILT_Y:
142 case ABS_MT_SLOT:
143 case ABS_MT_TOUCH_MAJOR:
144 case ABS_MT_TOUCH_MINOR:
145 case ABS_MT_WIDTH_MAJOR:
146 case ABS_MT_WIDTH_MINOR:
147 case ABS_MT_ORIENTATION:
148 case ABS_MT_POSITION_X:
149 case ABS_MT_POSITION_Y:
150 case ABS_MT_TOOL_TYPE:
151 case ABS_MT_BLOB_ID:
152 case ABS_MT_TRACKING_ID:
153 case ABS_MT_PRESSURE:
154 case ABS_MT_DISTANCE:
155 return INPUT_DEVICE_CLASS_TOUCH;
156 }
157 }
158
Michael Wright842500e2015-03-13 17:32:02 -0700159 // External stylus gets the pressure axis
160 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
161 if (axis == ABS_PRESSURE) {
162 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
163 }
164 }
165
Michael Wrightd02c5b62014-02-10 15:10:22 -0800166 // Joystick devices get the rest.
167 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
168}
169
170// --- EventHub::Device ---
171
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100172EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800173 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700174 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800175 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700176 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800178 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800179 memset(keyBitmask, 0, sizeof(keyBitmask));
180 memset(absBitmask, 0, sizeof(absBitmask));
181 memset(relBitmask, 0, sizeof(relBitmask));
182 memset(swBitmask, 0, sizeof(swBitmask));
183 memset(ledBitmask, 0, sizeof(ledBitmask));
184 memset(ffBitmask, 0, sizeof(ffBitmask));
185 memset(propBitmask, 0, sizeof(propBitmask));
186}
187
188EventHub::Device::~Device() {
189 close();
190 delete configuration;
191 delete virtualKeyMap;
192}
193
194void EventHub::Device::close() {
195 if (fd >= 0) {
196 ::close(fd);
197 fd = -1;
198 }
199}
200
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700201status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100202 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700203 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100204 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700205 return -errno;
206 }
207 enabled = true;
208 return OK;
209}
210
211status_t EventHub::Device::disable() {
212 close();
213 enabled = false;
214 return OK;
215}
216
217bool EventHub::Device::hasValidFd() {
218 return !isVirtual && enabled;
219}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800220
221// --- EventHub ---
222
Michael Wrightd02c5b62014-02-10 15:10:22 -0800223const int EventHub::EPOLL_MAX_EVENTS;
224
225EventHub::EventHub(void) :
226 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700227 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800228 mNeedToSendFinishedDeviceScan(false),
229 mNeedToReopenDevices(false), mNeedToScanDevices(true),
230 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
231 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
232
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800233 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800234 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800235
236 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800237 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
238 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
239 DEVICE_PATH, strerror(errno));
240 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
241 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
242 VIDEO_DEVICE_PATH, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800243
244 struct epoll_event eventItem;
245 memset(&eventItem, 0, sizeof(eventItem));
246 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700247 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800248 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
250
251 int wakeFds[2];
252 result = pipe(wakeFds);
253 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
254
255 mWakeReadPipeFd = wakeFds[0];
256 mWakeWritePipeFd = wakeFds[1];
257
258 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
259 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
260 errno);
261
262 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
263 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
264 errno);
265
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700266 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800267 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
268 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
269 errno);
270
271 int major, minor;
272 getLinuxRelease(&major, &minor);
273 // EPOLLWAKEUP was introduced in kernel 3.5
274 mUsingEpollWakeup = major > 3 || (major == 3 && minor >= 5);
275}
276
277EventHub::~EventHub(void) {
278 closeAllDevicesLocked();
279
280 while (mClosingDevices) {
281 Device* device = mClosingDevices;
282 mClosingDevices = device->next;
283 delete device;
284 }
285
286 ::close(mEpollFd);
287 ::close(mINotifyFd);
288 ::close(mWakeReadPipeFd);
289 ::close(mWakeWritePipeFd);
290
291 release_wake_lock(WAKE_LOCK_ID);
292}
293
294InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
295 AutoMutex _l(mLock);
296 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700297 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800298 return device->identifier;
299}
300
301uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
302 AutoMutex _l(mLock);
303 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700304 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 return device->classes;
306}
307
308int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
309 AutoMutex _l(mLock);
310 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700311 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800312 return device->controllerNumber;
313}
314
315void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
316 AutoMutex _l(mLock);
317 Device* device = getDeviceLocked(deviceId);
318 if (device && device->configuration) {
319 *outConfiguration = *device->configuration;
320 } else {
321 outConfiguration->clear();
322 }
323}
324
325status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
326 RawAbsoluteAxisInfo* outAxisInfo) const {
327 outAxisInfo->clear();
328
329 if (axis >= 0 && axis <= ABS_MAX) {
330 AutoMutex _l(mLock);
331
332 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700333 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334 struct input_absinfo info;
335 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
336 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100337 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800338 return -errno;
339 }
340
341 if (info.minimum != info.maximum) {
342 outAxisInfo->valid = true;
343 outAxisInfo->minValue = info.minimum;
344 outAxisInfo->maxValue = info.maximum;
345 outAxisInfo->flat = info.flat;
346 outAxisInfo->fuzz = info.fuzz;
347 outAxisInfo->resolution = info.resolution;
348 }
349 return OK;
350 }
351 }
352 return -1;
353}
354
355bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
356 if (axis >= 0 && axis <= REL_MAX) {
357 AutoMutex _l(mLock);
358
359 Device* device = getDeviceLocked(deviceId);
360 if (device) {
361 return test_bit(axis, device->relBitmask);
362 }
363 }
364 return false;
365}
366
367bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
368 if (property >= 0 && property <= INPUT_PROP_MAX) {
369 AutoMutex _l(mLock);
370
371 Device* device = getDeviceLocked(deviceId);
372 if (device) {
373 return test_bit(property, device->propBitmask);
374 }
375 }
376 return false;
377}
378
379int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
380 if (scanCode >= 0 && scanCode <= KEY_MAX) {
381 AutoMutex _l(mLock);
382
383 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700384 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800385 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
386 memset(keyState, 0, sizeof(keyState));
387 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
388 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
389 }
390 }
391 }
392 return AKEY_STATE_UNKNOWN;
393}
394
395int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
396 AutoMutex _l(mLock);
397
398 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700399 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400 Vector<int32_t> scanCodes;
401 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
402 if (scanCodes.size() != 0) {
403 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
404 memset(keyState, 0, sizeof(keyState));
405 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
406 for (size_t i = 0; i < scanCodes.size(); i++) {
407 int32_t sc = scanCodes.itemAt(i);
408 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
409 return AKEY_STATE_DOWN;
410 }
411 }
412 return AKEY_STATE_UP;
413 }
414 }
415 }
416 return AKEY_STATE_UNKNOWN;
417}
418
419int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
420 if (sw >= 0 && sw <= SW_MAX) {
421 AutoMutex _l(mLock);
422
423 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700424 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800425 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
426 memset(swState, 0, sizeof(swState));
427 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
428 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
429 }
430 }
431 }
432 return AKEY_STATE_UNKNOWN;
433}
434
435status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
436 *outValue = 0;
437
438 if (axis >= 0 && axis <= ABS_MAX) {
439 AutoMutex _l(mLock);
440
441 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700442 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 struct input_absinfo info;
444 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
445 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100446 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 return -errno;
448 }
449
450 *outValue = info.value;
451 return OK;
452 }
453 }
454 return -1;
455}
456
457bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
458 const int32_t* keyCodes, uint8_t* outFlags) const {
459 AutoMutex _l(mLock);
460
461 Device* device = getDeviceLocked(deviceId);
462 if (device && device->keyMap.haveKeyLayout()) {
463 Vector<int32_t> scanCodes;
464 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
465 scanCodes.clear();
466
467 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
468 keyCodes[codeIndex], &scanCodes);
469 if (! err) {
470 // check the possible scan codes identified by the layout map against the
471 // map of codes actually emitted by the driver
472 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
473 if (test_bit(scanCodes[sc], device->keyBitmask)) {
474 outFlags[codeIndex] = 1;
475 break;
476 }
477 }
478 }
479 }
480 return true;
481 }
482 return false;
483}
484
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700485status_t EventHub::mapKey(int32_t deviceId,
486 int32_t scanCode, int32_t usageCode, int32_t metaState,
487 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800488 AutoMutex _l(mLock);
489 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700490 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491
492 if (device) {
493 // Check the key character map first.
494 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700495 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
497 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700498 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 }
500 }
501
502 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700503 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800504 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700505 status = NO_ERROR;
506 }
507 }
508
509 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700510 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700511 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
512 } else {
513 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 }
515 }
516 }
517
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700518 if (status != NO_ERROR) {
519 *outKeycode = 0;
520 *outFlags = 0;
521 *outMetaState = metaState;
522 }
523
524 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525}
526
527status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
528 AutoMutex _l(mLock);
529 Device* device = getDeviceLocked(deviceId);
530
531 if (device && device->keyMap.haveKeyLayout()) {
532 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
533 if (err == NO_ERROR) {
534 return NO_ERROR;
535 }
536 }
537
538 return NAME_NOT_FOUND;
539}
540
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100541void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800542 AutoMutex _l(mLock);
543
544 mExcludedDevices = devices;
545}
546
547bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
548 AutoMutex _l(mLock);
549 Device* device = getDeviceLocked(deviceId);
550 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
551 if (test_bit(scanCode, device->keyBitmask)) {
552 return true;
553 }
554 }
555 return false;
556}
557
558bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
559 AutoMutex _l(mLock);
560 Device* device = getDeviceLocked(deviceId);
561 int32_t sc;
562 if (device && mapLed(device, led, &sc) == NO_ERROR) {
563 if (test_bit(sc, device->ledBitmask)) {
564 return true;
565 }
566 }
567 return false;
568}
569
570void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
571 AutoMutex _l(mLock);
572 Device* device = getDeviceLocked(deviceId);
573 setLedStateLocked(device, led, on);
574}
575
576void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
577 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700578 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 struct input_event ev;
580 ev.time.tv_sec = 0;
581 ev.time.tv_usec = 0;
582 ev.type = EV_LED;
583 ev.code = sc;
584 ev.value = on ? 1 : 0;
585
586 ssize_t nWrite;
587 do {
588 nWrite = write(device->fd, &ev, sizeof(struct input_event));
589 } while (nWrite == -1 && errno == EINTR);
590 }
591}
592
593void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
594 Vector<VirtualKeyDefinition>& outVirtualKeys) const {
595 outVirtualKeys.clear();
596
597 AutoMutex _l(mLock);
598 Device* device = getDeviceLocked(deviceId);
599 if (device && device->virtualKeyMap) {
600 outVirtualKeys.appendVector(device->virtualKeyMap->getVirtualKeys());
601 }
602}
603
604sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
605 AutoMutex _l(mLock);
606 Device* device = getDeviceLocked(deviceId);
607 if (device) {
608 return device->getKeyCharacterMap();
609 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700610 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611}
612
613bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
614 const sp<KeyCharacterMap>& map) {
615 AutoMutex _l(mLock);
616 Device* device = getDeviceLocked(deviceId);
617 if (device) {
618 if (map != device->overlayKeyMap) {
619 device->overlayKeyMap = map;
620 device->combinedKeyMap = KeyCharacterMap::combine(
621 device->keyMap.keyCharacterMap, map);
622 return true;
623 }
624 }
625 return false;
626}
627
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100628static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
629 std::string rawDescriptor;
630 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800631 identifier.product);
632 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100633 if (!identifier.uniqueId.empty()) {
634 rawDescriptor += "uniqueId:";
635 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100637 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 }
639
640 if (identifier.vendor == 0 && identifier.product == 0) {
641 // If we don't know the vendor and product id, then the device is probably
642 // built-in so we need to rely on other information to uniquely identify
643 // the input device. Usually we try to avoid relying on the device name or
644 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100645 if (!identifier.name.empty()) {
646 rawDescriptor += "name:";
647 rawDescriptor += identifier.name;
648 } else if (!identifier.location.empty()) {
649 rawDescriptor += "location:";
650 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 }
652 }
653 identifier.descriptor = sha1(rawDescriptor);
654 return rawDescriptor;
655}
656
657void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
658 // Compute a device descriptor that uniquely identifies the device.
659 // The descriptor is assumed to be a stable identifier. Its value should not
660 // change between reboots, reconnections, firmware updates or new releases
661 // of Android. In practice we sometimes get devices that cannot be uniquely
662 // identified. In this case we enforce uniqueness between connected devices.
663 // Ideally, we also want the descriptor to be short and relatively opaque.
664
665 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100666 std::string rawDescriptor = generateDescriptor(identifier);
667 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 // If it didn't have a unique id check for conflicts and enforce
669 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700670 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 identifier.nonce++;
672 rawDescriptor = generateDescriptor(identifier);
673 }
674 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100675 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
676 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800677}
678
679void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
680 AutoMutex _l(mLock);
681 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700682 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 ff_effect effect;
684 memset(&effect, 0, sizeof(effect));
685 effect.type = FF_RUMBLE;
686 effect.id = device->ffEffectId;
687 effect.u.rumble.strong_magnitude = 0xc000;
688 effect.u.rumble.weak_magnitude = 0xc000;
689 effect.replay.length = (duration + 999999LL) / 1000000LL;
690 effect.replay.delay = 0;
691 if (ioctl(device->fd, EVIOCSFF, &effect)) {
692 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100693 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 return;
695 }
696 device->ffEffectId = effect.id;
697
698 struct input_event ev;
699 ev.time.tv_sec = 0;
700 ev.time.tv_usec = 0;
701 ev.type = EV_FF;
702 ev.code = device->ffEffectId;
703 ev.value = 1;
704 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
705 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100706 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800707 return;
708 }
709 device->ffEffectPlaying = true;
710 }
711}
712
713void EventHub::cancelVibrate(int32_t deviceId) {
714 AutoMutex _l(mLock);
715 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700716 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717 if (device->ffEffectPlaying) {
718 device->ffEffectPlaying = false;
719
720 struct input_event ev;
721 ev.time.tv_sec = 0;
722 ev.time.tv_usec = 0;
723 ev.type = EV_FF;
724 ev.code = device->ffEffectId;
725 ev.value = 0;
726 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
727 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100728 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 return;
730 }
731 }
732 }
733}
734
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100735EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 size_t size = mDevices.size();
737 for (size_t i = 0; i < size; i++) {
738 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100739 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800740 return device;
741 }
742 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700743 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744}
745
746EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
747 if (deviceId == BUILT_IN_KEYBOARD_ID) {
748 deviceId = mBuiltInKeyboardId;
749 }
750 ssize_t index = mDevices.indexOfKey(deviceId);
751 return index >= 0 ? mDevices.valueAt(index) : NULL;
752}
753
754EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
755 for (size_t i = 0; i < mDevices.size(); i++) {
756 Device* device = mDevices.valueAt(i);
757 if (device->path == devicePath) {
758 return device;
759 }
760 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700761 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762}
763
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700764/**
765 * The file descriptor could be either input device, or a video device (associated with a
766 * specific input device). Check both cases here, and return the device that this event
767 * belongs to. Caller can compare the fd's once more to determine event type.
768 * Looks through all input devices, and only attached video devices. Unattached video
769 * devices are ignored.
770 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700771EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
772 for (size_t i = 0; i < mDevices.size(); i++) {
773 Device* device = mDevices.valueAt(i);
774 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700775 // This is an input device event
776 return device;
777 }
778 if (device->videoDevice && device->videoDevice->getFd() == fd) {
779 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700780 return device;
781 }
782 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700783 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
784 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700785 return nullptr;
786}
787
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
789 ALOG_ASSERT(bufferSize >= 1);
790
791 AutoMutex _l(mLock);
792
793 struct input_event readBuffer[bufferSize];
794
795 RawEvent* event = buffer;
796 size_t capacity = bufferSize;
797 bool awoken = false;
798 for (;;) {
799 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
800
801 // Reopen input devices if needed.
802 if (mNeedToReopenDevices) {
803 mNeedToReopenDevices = false;
804
805 ALOGI("Reopening all input devices due to a configuration change.");
806
807 closeAllDevicesLocked();
808 mNeedToScanDevices = true;
809 break; // return to the caller before we actually rescan
810 }
811
812 // Report any devices that had last been added/removed.
813 while (mClosingDevices) {
814 Device* device = mClosingDevices;
815 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100816 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800817 mClosingDevices = device->next;
818 event->when = now;
819 event->deviceId = device->id == mBuiltInKeyboardId ? BUILT_IN_KEYBOARD_ID : device->id;
820 event->type = DEVICE_REMOVED;
821 event += 1;
822 delete device;
823 mNeedToSendFinishedDeviceScan = true;
824 if (--capacity == 0) {
825 break;
826 }
827 }
828
829 if (mNeedToScanDevices) {
830 mNeedToScanDevices = false;
831 scanDevicesLocked();
832 mNeedToSendFinishedDeviceScan = true;
833 }
834
Yi Kong9b14ac62018-07-17 13:48:38 -0700835 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 Device* device = mOpeningDevices;
837 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100838 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 mOpeningDevices = device->next;
840 event->when = now;
841 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
842 event->type = DEVICE_ADDED;
843 event += 1;
844 mNeedToSendFinishedDeviceScan = true;
845 if (--capacity == 0) {
846 break;
847 }
848 }
849
850 if (mNeedToSendFinishedDeviceScan) {
851 mNeedToSendFinishedDeviceScan = false;
852 event->when = now;
853 event->type = FINISHED_DEVICE_SCAN;
854 event += 1;
855 if (--capacity == 0) {
856 break;
857 }
858 }
859
860 // Grab the next input event.
861 bool deviceChanged = false;
862 while (mPendingEventIndex < mPendingEventCount) {
863 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700864 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 if (eventItem.events & EPOLLIN) {
866 mPendingINotify = true;
867 } else {
868 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
869 }
870 continue;
871 }
872
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700873 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 if (eventItem.events & EPOLLIN) {
875 ALOGV("awoken after wake()");
876 awoken = true;
877 char buffer[16];
878 ssize_t nRead;
879 do {
880 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
881 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
882 } else {
883 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
884 eventItem.events);
885 }
886 continue;
887 }
888
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700889 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700890 if (!device) {
891 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700892 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700893 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 continue;
895 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700896 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
897 if (eventItem.events & EPOLLIN) {
898 size_t numFrames = device->videoDevice->readAndQueueFrames();
899 if (numFrames == 0) {
900 ALOGE("Received epoll event for video device %s, but could not read frame",
901 device->videoDevice->getName().c_str());
902 }
903 } else if (eventItem.events & EPOLLHUP) {
904 // TODO(b/121395353) - consider adding EPOLLRDHUP
905 ALOGI("Removing video device %s due to epoll hang-up event.",
906 device->videoDevice->getName().c_str());
907 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
908 device->videoDevice = nullptr;
909 } else {
910 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
911 eventItem.events, device->videoDevice->getName().c_str());
912 ALOG_ASSERT(!DEBUG);
913 }
914 continue;
915 }
916 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800917 if (eventItem.events & EPOLLIN) {
918 int32_t readSize = read(device->fd, readBuffer,
919 sizeof(struct input_event) * capacity);
920 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
921 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700922 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
923 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924 device->fd, readSize, bufferSize, capacity, errno);
925 deviceChanged = true;
926 closeDeviceLocked(device);
927 } else if (readSize < 0) {
928 if (errno != EAGAIN && errno != EINTR) {
929 ALOGW("could not get event (errno=%d)", errno);
930 }
931 } else if ((readSize % sizeof(struct input_event)) != 0) {
932 ALOGE("could not get event (wrong size: %d)", readSize);
933 } else {
934 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
935
936 size_t count = size_t(readSize) / sizeof(struct input_event);
937 for (size_t i = 0; i < count; i++) {
938 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800939 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800940 event->deviceId = deviceId;
941 event->type = iev.type;
942 event->code = iev.code;
943 event->value = iev.value;
944 event += 1;
945 capacity -= 1;
946 }
947 if (capacity == 0) {
948 // The result buffer is full. Reset the pending event index
949 // so we will try to read the device again on the next iteration.
950 mPendingEventIndex -= 1;
951 break;
952 }
953 }
954 } else if (eventItem.events & EPOLLHUP) {
955 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100956 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957 deviceChanged = true;
958 closeDeviceLocked(device);
959 } else {
960 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100961 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 }
963 }
964
965 // readNotify() will modify the list of devices so this must be done after
966 // processing all other events to ensure that we read all remaining events
967 // before closing the devices.
968 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
969 mPendingINotify = false;
970 readNotifyLocked();
971 deviceChanged = true;
972 }
973
974 // Report added or removed devices immediately.
975 if (deviceChanged) {
976 continue;
977 }
978
979 // Return now if we have collected any events or if we were explicitly awoken.
980 if (event != buffer || awoken) {
981 break;
982 }
983
984 // Poll for events. Mind the wake lock dance!
985 // We hold a wake lock at all times except during epoll_wait(). This works due to some
986 // subtle choreography. When a device driver has pending (unread) events, it acquires
987 // a kernel wake lock. However, once the last pending event has been read, the device
988 // driver will release the kernel wake lock. To prevent the system from going to sleep
989 // when this happens, the EventHub holds onto its own user wake lock while the client
990 // is processing events. Thus the system can only sleep if there are no events
991 // pending or currently being processed.
992 //
993 // The timeout is advisory only. If the device is asleep, it will not wake just to
994 // service the timeout.
995 mPendingEventIndex = 0;
996
997 mLock.unlock(); // release lock before poll, must be before release_wake_lock
998 release_wake_lock(WAKE_LOCK_ID);
999
1000 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1001
1002 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1003 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1004
1005 if (pollResult == 0) {
1006 // Timed out.
1007 mPendingEventCount = 0;
1008 break;
1009 }
1010
1011 if (pollResult < 0) {
1012 // An error occurred.
1013 mPendingEventCount = 0;
1014
1015 // Sleep after errors to avoid locking up the system.
1016 // Hopefully the error is transient.
1017 if (errno != EINTR) {
1018 ALOGW("poll failed (errno=%d)\n", errno);
1019 usleep(100000);
1020 }
1021 } else {
1022 // Some events occurred.
1023 mPendingEventCount = size_t(pollResult);
1024 }
1025 }
1026
1027 // All done, return the number of events we read.
1028 return event - buffer;
1029}
1030
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001031std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1032 AutoMutex _l(mLock);
1033
1034 Device* device = getDeviceLocked(deviceId);
1035 if (!device || !device->videoDevice) {
1036 return {};
1037 }
1038 return device->videoDevice->consumeFrames();
1039}
1040
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041void EventHub::wake() {
1042 ALOGV("wake() called");
1043
1044 ssize_t nWrite;
1045 do {
1046 nWrite = write(mWakeWritePipeFd, "W", 1);
1047 } while (nWrite == -1 && errno == EINTR);
1048
1049 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001050 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 }
1052}
1053
1054void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001055 status_t result = scanDirLocked(DEVICE_PATH);
1056 if(result < 0) {
1057 ALOGE("scan dir failed for %s", DEVICE_PATH);
1058 }
1059 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1060 if (result != OK) {
1061 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 }
1063 if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
1064 createVirtualKeyboardLocked();
1065 }
1066}
1067
1068// ----------------------------------------------------------------------------
1069
1070static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1071 const uint8_t* end = array + endIndex;
1072 array += startIndex;
1073 while (array != end) {
1074 if (*(array++) != 0) {
1075 return true;
1076 }
1077 }
1078 return false;
1079}
1080
1081static const int32_t GAMEPAD_KEYCODES[] = {
1082 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1083 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1084 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1085 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1086 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1087 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088};
1089
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001090status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001091 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001092 struct epoll_event eventItem = {};
1093 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1094 eventItem.data.fd = fd;
1095 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1096 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001097 return -errno;
1098 }
1099 return OK;
1100}
1101
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001102status_t EventHub::unregisterFdFromEpoll(int fd) {
1103 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1104 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1105 return -errno;
1106 }
1107 return OK;
1108}
1109
1110status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1111 if (device == nullptr) {
1112 if (DEBUG) {
1113 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1114 }
1115 return BAD_VALUE;
1116 }
1117 status_t result = registerFdForEpoll(device->fd);
1118 if (result != OK) {
1119 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001120 return result;
1121 }
1122 if (device->videoDevice) {
1123 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001124 }
1125 return result;
1126}
1127
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001128void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1129 status_t result = registerFdForEpoll(videoDevice.getFd());
1130 if (result != OK) {
1131 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1132 }
1133}
1134
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001135status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1136 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001137 status_t result = unregisterFdFromEpoll(device->fd);
1138 if (result != OK) {
1139 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1140 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001141 }
1142 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001143 if (device->videoDevice) {
1144 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1145 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001146 return OK;
1147}
1148
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001149void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1150 if (videoDevice.hasValidFd()) {
1151 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1152 if (result != OK) {
1153 ALOGW("Could not remove video device fd from epoll for device: %s",
1154 videoDevice.getName().c_str());
1155 }
1156 }
1157}
1158
1159status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 char buffer[80];
1161
1162 ALOGV("Opening device: %s", devicePath);
1163
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001164 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 if(fd < 0) {
1166 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1167 return -1;
1168 }
1169
1170 InputDeviceIdentifier identifier;
1171
1172 // Get device name.
1173 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001174 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001175 } else {
1176 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001177 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 }
1179
1180 // Check to see if the device is on our excluded list
1181 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001182 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001184 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 close(fd);
1186 return -1;
1187 }
1188 }
1189
1190 // Get device driver version.
1191 int driverVersion;
1192 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1193 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1194 close(fd);
1195 return -1;
1196 }
1197
1198 // Get device identifier.
1199 struct input_id inputId;
1200 if(ioctl(fd, EVIOCGID, &inputId)) {
1201 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1202 close(fd);
1203 return -1;
1204 }
1205 identifier.bus = inputId.bustype;
1206 identifier.product = inputId.product;
1207 identifier.vendor = inputId.vendor;
1208 identifier.version = inputId.version;
1209
1210 // Get device physical location.
1211 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1212 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1213 } else {
1214 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001215 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001216 }
1217
1218 // Get device unique id.
1219 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1220 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1221 } else {
1222 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001223 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 }
1225
1226 // Fill in the descriptor.
1227 assignDescriptorLocked(identifier);
1228
Michael Wrightd02c5b62014-02-10 15:10:22 -08001229 // Allocate device. (The device object takes ownership of the fd at this point.)
1230 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001231 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232
1233 ALOGV("add device %d: %s\n", deviceId, devicePath);
1234 ALOGV(" bus: %04x\n"
1235 " vendor %04x\n"
1236 " product %04x\n"
1237 " version %04x\n",
1238 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001239 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1240 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1241 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1242 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 ALOGV(" driver: v%d.%d.%d\n",
1244 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1245
1246 // Load the configuration file for the device.
1247 loadConfigurationLocked(device);
1248
1249 // Figure out the kinds of events the device reports.
1250 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1251 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1252 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1253 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1254 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1255 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1256 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1257
1258 // See if this is a keyboard. Ignore everything in the button range except for
1259 // joystick and gamepad buttons which are handled like keyboards for the most part.
1260 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1261 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1262 sizeof_bit_array(KEY_MAX + 1));
1263 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1264 sizeof_bit_array(BTN_MOUSE))
1265 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1266 sizeof_bit_array(BTN_DIGI));
1267 if (haveKeyboardKeys || haveGamepadButtons) {
1268 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1269 }
1270
1271 // See if this is a cursor device such as a trackball or mouse.
1272 if (test_bit(BTN_MOUSE, device->keyBitmask)
1273 && test_bit(REL_X, device->relBitmask)
1274 && test_bit(REL_Y, device->relBitmask)) {
1275 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1276 }
1277
Prashant Malani1941ff52015-08-11 18:29:28 -07001278 // See if this is a rotary encoder type device.
1279 String8 deviceType = String8();
1280 if (device->configuration &&
1281 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1282 if (!deviceType.compare(String8("rotaryEncoder"))) {
1283 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1284 }
1285 }
1286
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287 // See if this is a touch pad.
1288 // Is this a new modern multi-touch driver?
1289 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1290 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1291 // Some joysticks such as the PS3 controller report axes that conflict
1292 // with the ABS_MT range. Try to confirm that the device really is
1293 // a touch screen.
1294 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1295 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1296 }
1297 // Is this an old style single-touch driver?
1298 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1299 && test_bit(ABS_X, device->absBitmask)
1300 && test_bit(ABS_Y, device->absBitmask)) {
1301 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001302 // Is this a BT stylus?
1303 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1304 test_bit(BTN_TOUCH, device->keyBitmask))
1305 && !test_bit(ABS_X, device->absBitmask)
1306 && !test_bit(ABS_Y, device->absBitmask)) {
1307 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1308 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1309 // can fuse it with the touch screen data, so just take them back. Note this means an
1310 // external stylus cannot also be a keyboard device.
1311 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001312 }
1313
1314 // See if this device is a joystick.
1315 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1316 // from other devices such as accelerometers that also have absolute axes.
1317 if (haveGamepadButtons) {
1318 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1319 for (int i = 0; i <= ABS_MAX; i++) {
1320 if (test_bit(i, device->absBitmask)
1321 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1322 device->classes = assumedClasses;
1323 break;
1324 }
1325 }
1326 }
1327
1328 // Check whether this device has switches.
1329 for (int i = 0; i <= SW_MAX; i++) {
1330 if (test_bit(i, device->swBitmask)) {
1331 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1332 break;
1333 }
1334 }
1335
1336 // Check whether this device supports the vibrator.
1337 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1338 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1339 }
1340
1341 // Configure virtual keys.
1342 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1343 // Load the virtual keys for the touch screen, if any.
1344 // We do this now so that we can make sure to load the keymap if necessary.
1345 status_t status = loadVirtualKeyMapLocked(device);
1346 if (!status) {
1347 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1348 }
1349 }
1350
1351 // Load the key map.
1352 // We need to do this for joysticks too because the key layout may specify axes.
1353 status_t keyMapStatus = NAME_NOT_FOUND;
1354 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1355 // Load the keymap for the device.
1356 keyMapStatus = loadKeyMapLocked(device);
1357 }
1358
1359 // Configure the keyboard, gamepad or virtual keyboard.
1360 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1361 // Register the keyboard as a built-in keyboard if it is eligible.
1362 if (!keyMapStatus
1363 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1364 && isEligibleBuiltInKeyboard(device->identifier,
1365 device->configuration, &device->keyMap)) {
1366 mBuiltInKeyboardId = device->id;
1367 }
1368
1369 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1370 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1371 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1372 }
1373
1374 // See if this device has a DPAD.
1375 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1376 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1377 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1378 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1379 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1380 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1381 }
1382
1383 // See if this device has a gamepad.
1384 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1385 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1386 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1387 break;
1388 }
1389 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 }
1391
1392 // If the device isn't recognized as something we handle, don't monitor it.
1393 if (device->classes == 0) {
1394 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001395 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001396 delete device;
1397 return -1;
1398 }
1399
Tim Kilbourn063ff532015-04-08 10:26:18 -07001400 // Determine whether the device has a mic.
1401 if (deviceHasMicLocked(device)) {
1402 device->classes |= INPUT_DEVICE_CLASS_MIC;
1403 }
1404
Michael Wrightd02c5b62014-02-10 15:10:22 -08001405 // Determine whether the device is external or internal.
1406 if (isExternalDeviceLocked(device)) {
1407 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1408 }
1409
Michael Wright42f2c6a2014-03-12 10:33:03 -07001410 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1411 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001413 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 }
1415
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001416 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001417 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001418 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1419 if (device->identifier.name == videoDevice->getName()) {
1420 device->videoDevice = std::move(videoDevice);
1421 break;
1422 }
1423 }
1424 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1425 mUnattachedVideoDevices.end(),
1426 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1427 return videoDevice == nullptr; }), mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001428
1429 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 delete device;
1431 return -1;
1432 }
1433
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001434 configureFd(device);
1435
1436 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1437 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001438 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001439 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001440 device->configurationFile.c_str(),
1441 device->keyMap.keyLayoutFile.c_str(),
1442 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001443 toString(mBuiltInKeyboardId == deviceId));
1444
1445 addDeviceLocked(device);
1446 return OK;
1447}
1448
1449void EventHub::configureFd(Device* device) {
1450 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1451 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1452 // Disable kernel key repeat since we handle it ourselves
1453 unsigned int repeatRate[] = {0, 0};
1454 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1455 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001456 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001457 }
1458 }
1459
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001460 std::string wakeMechanism = "EPOLLWAKEUP";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001461 if (!mUsingEpollWakeup) {
1462#ifndef EVIOCSSUSPENDBLOCK
1463 // uapi headers don't include EVIOCSSUSPENDBLOCK, and future kernels
1464 // will use an epoll flag instead, so as long as we want to support
1465 // this feature, we need to be prepared to define the ioctl ourselves.
1466#define EVIOCSSUSPENDBLOCK _IOW('E', 0x91, int)
1467#endif
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001468 if (ioctl(device->fd, EVIOCSSUSPENDBLOCK, 1)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 wakeMechanism = "<none>";
1470 } else {
1471 wakeMechanism = "EVIOCSSUSPENDBLOCK";
1472 }
1473 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1475 // associated with input events. This is important because the input system
1476 // uses the timestamps extensively and assumes they were recorded using the monotonic
1477 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001478 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001479 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001480 ALOGI("wakeMechanism=%s, usingClockIoctl=%s", wakeMechanism.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001481 toString(usingClockIoctl));
1482}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001483
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001484void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1485 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1486 if (!videoDevice) {
1487 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1488 return;
1489 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001490 // Transfer ownership of this video device to a matching input device
1491 for (size_t i = 0; i < mDevices.size(); i++) {
1492 Device* device = mDevices.valueAt(i);
1493 if (videoDevice->getName() == device->identifier.name) {
1494 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001495 if (device->enabled) {
1496 registerVideoDeviceForEpollLocked(*device->videoDevice);
1497 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001498 return;
1499 }
1500 }
1501
1502 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1503 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001504 ALOGI("Adding video device %s to list of unattached video devices",
1505 videoDevice->getName().c_str());
1506 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1507}
1508
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001509bool EventHub::isDeviceEnabled(int32_t deviceId) {
1510 AutoMutex _l(mLock);
1511 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001512 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001513 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1514 return false;
1515 }
1516 return device->enabled;
1517}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001519status_t EventHub::enableDevice(int32_t deviceId) {
1520 AutoMutex _l(mLock);
1521 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001522 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001523 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1524 return BAD_VALUE;
1525 }
1526 if (device->enabled) {
1527 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1528 return OK;
1529 }
1530 status_t result = device->enable();
1531 if (result != OK) {
1532 ALOGE("Failed to enable device %" PRId32, deviceId);
1533 return result;
1534 }
1535
1536 configureFd(device);
1537
1538 return registerDeviceForEpollLocked(device);
1539}
1540
1541status_t EventHub::disableDevice(int32_t deviceId) {
1542 AutoMutex _l(mLock);
1543 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001544 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001545 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1546 return BAD_VALUE;
1547 }
1548 if (!device->enabled) {
1549 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1550 return OK;
1551 }
1552 unregisterDeviceFromEpollLocked(device);
1553 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001554}
1555
1556void EventHub::createVirtualKeyboardLocked() {
1557 InputDeviceIdentifier identifier;
1558 identifier.name = "Virtual";
1559 identifier.uniqueId = "<virtual>";
1560 assignDescriptorLocked(identifier);
1561
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001562 Device* device = new Device(-1, VIRTUAL_KEYBOARD_ID, "<virtual>", identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1564 | INPUT_DEVICE_CLASS_ALPHAKEY
1565 | INPUT_DEVICE_CLASS_DPAD
1566 | INPUT_DEVICE_CLASS_VIRTUAL;
1567 loadKeyMapLocked(device);
1568 addDeviceLocked(device);
1569}
1570
1571void EventHub::addDeviceLocked(Device* device) {
1572 mDevices.add(device->id, device);
1573 device->next = mOpeningDevices;
1574 mOpeningDevices = device;
1575}
1576
1577void EventHub::loadConfigurationLocked(Device* device) {
1578 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1579 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001580 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001581 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001582 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001584 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 &device->configuration);
1586 if (status) {
1587 ALOGE("Error loading input device configuration file for device '%s'. "
1588 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001589 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 }
1591 }
1592}
1593
1594status_t EventHub::loadVirtualKeyMapLocked(Device* device) {
1595 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001596 std::string path;
1597 path += "/sys/board_properties/virtualkeys.";
1598 path += device->identifier.name;
1599 if (access(path.c_str(), R_OK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001600 return NAME_NOT_FOUND;
1601 }
1602 return VirtualKeyMap::load(path, &device->virtualKeyMap);
1603}
1604
1605status_t EventHub::loadKeyMapLocked(Device* device) {
1606 return device->keyMap.load(device->identifier, device->configuration);
1607}
1608
1609bool EventHub::isExternalDeviceLocked(Device* device) {
1610 if (device->configuration) {
1611 bool value;
1612 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1613 return !value;
1614 }
1615 }
1616 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1617}
1618
Tim Kilbourn063ff532015-04-08 10:26:18 -07001619bool EventHub::deviceHasMicLocked(Device* device) {
1620 if (device->configuration) {
1621 bool value;
1622 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1623 return value;
1624 }
1625 }
1626 return false;
1627}
1628
Michael Wrightd02c5b62014-02-10 15:10:22 -08001629int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1630 if (mControllerNumbers.isFull()) {
1631 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001632 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 return 0;
1634 }
1635 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1636 // one
1637 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1638}
1639
1640void EventHub::releaseControllerNumberLocked(Device* device) {
1641 int32_t num = device->controllerNumber;
1642 device->controllerNumber= 0;
1643 if (num == 0) {
1644 return;
1645 }
1646 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1647}
1648
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001649void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001650 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1651 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1652 }
1653}
1654
1655bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001656 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001657 return false;
1658 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001659
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 Vector<int32_t> scanCodes;
1661 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1662 const size_t N = scanCodes.size();
1663 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
1664 int32_t sc = scanCodes.itemAt(i);
1665 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1666 return true;
1667 }
1668 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001669
Michael Wrightd02c5b62014-02-10 15:10:22 -08001670 return false;
1671}
1672
1673status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001674 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001675 return NAME_NOT_FOUND;
1676 }
1677
1678 int32_t scanCode;
1679 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1680 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1681 *outScanCode = scanCode;
1682 return NO_ERROR;
1683 }
1684 }
1685 return NAME_NOT_FOUND;
1686}
1687
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001688void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689 Device* device = getDeviceByPathLocked(devicePath);
1690 if (device) {
1691 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001692 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001693 }
1694 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001695}
1696
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001697/**
1698 * Find the video device by filename, and close it.
1699 * The video device is closed by path during an inotify event, where we don't have the
1700 * additional context about the video device fd, or the associated input device.
1701 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001702void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001703 // A video device may be owned by an existing input device, or it may be stored in
1704 // the mUnattachedVideoDevices queue. Check both locations.
1705 for (size_t i = 0; i < mDevices.size(); i++) {
1706 Device* device = mDevices.valueAt(i);
1707 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001708 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001709 device->videoDevice = nullptr;
1710 return;
1711 }
1712 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001713 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1714 mUnattachedVideoDevices.end(), [&devicePath](
1715 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1716 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001717}
1718
1719void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001720 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001721 while (mDevices.size() > 0) {
1722 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1723 }
1724}
1725
1726void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001727 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001728 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001729 device->fd, device->classes);
1730
1731 if (device->id == mBuiltInKeyboardId) {
1732 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001733 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1735 }
1736
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001737 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001738 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001739 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001740 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1741 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742
1743 releaseControllerNumberLocked(device);
1744
1745 mDevices.removeItem(device->id);
1746 device->close();
1747
1748 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001749 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001750 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001751 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001752 if (entry == device) {
1753 found = true;
1754 break;
1755 }
1756 pred = entry;
1757 entry = entry->next;
1758 }
1759 if (found) {
1760 // Unlink the device from the opening devices list then delete it.
1761 // We don't need to tell the client that the device was closed because
1762 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001763 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764 if (pred) {
1765 pred->next = device->next;
1766 } else {
1767 mOpeningDevices = device->next;
1768 }
1769 delete device;
1770 } else {
1771 // Link into closing devices list.
1772 // The device will be deleted later after we have informed the client.
1773 device->next = mClosingDevices;
1774 mClosingDevices = device;
1775 }
1776}
1777
1778status_t EventHub::readNotifyLocked() {
1779 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 char event_buf[512];
1781 int event_size;
1782 int event_pos = 0;
1783 struct inotify_event *event;
1784
1785 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1786 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1787 if(res < (int)sizeof(*event)) {
1788 if(errno == EINTR)
1789 return 0;
1790 ALOGW("could not get event, %s\n", strerror(errno));
1791 return -1;
1792 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793
1794 while(res >= (int)sizeof(*event)) {
1795 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001797 if (event->wd == mInputWd) {
1798 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1799 if(event->mask & IN_CREATE) {
1800 openDeviceLocked(filename.c_str());
1801 } else {
1802 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1803 closeDeviceByPathLocked(filename.c_str());
1804 }
1805 }
1806 else if (event->wd == mVideoWd) {
1807 if (isV4lTouchNode(event->name)) {
1808 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001809 if (event->mask & IN_CREATE) {
1810 openVideoDeviceLocked(filename);
1811 } else {
1812 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1813 closeVideoDeviceByPathLocked(filename);
1814 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001815 }
1816 }
1817 else {
1818 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001819 }
1820 }
1821 event_size = sizeof(*event) + event->len;
1822 res -= event_size;
1823 event_pos += event_size;
1824 }
1825 return 0;
1826}
1827
1828status_t EventHub::scanDirLocked(const char *dirname)
1829{
1830 char devname[PATH_MAX];
1831 char *filename;
1832 DIR *dir;
1833 struct dirent *de;
1834 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001835 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001836 return -1;
1837 strcpy(devname, dirname);
1838 filename = devname + strlen(devname);
1839 *filename++ = '/';
1840 while((de = readdir(dir))) {
1841 if(de->d_name[0] == '.' &&
1842 (de->d_name[1] == '\0' ||
1843 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1844 continue;
1845 strcpy(filename, de->d_name);
1846 openDeviceLocked(devname);
1847 }
1848 closedir(dir);
1849 return 0;
1850}
1851
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001852/**
1853 * Look for all dirname/v4l-touch* devices, and open them.
1854 */
1855status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1856{
1857 DIR* dir;
1858 struct dirent* de;
1859 dir = opendir(dirname.c_str());
1860 if(!dir) {
1861 ALOGE("Could not open video directory %s", dirname.c_str());
1862 return BAD_VALUE;
1863 }
1864
1865 while((de = readdir(dir))) {
1866 const char* name = de->d_name;
1867 if (isV4lTouchNode(name)) {
1868 ALOGI("Found touch video device %s", name);
1869 openVideoDeviceLocked(dirname + "/" + name);
1870 }
1871 }
1872 closedir(dir);
1873 return OK;
1874}
1875
Michael Wrightd02c5b62014-02-10 15:10:22 -08001876void EventHub::requestReopenDevices() {
1877 ALOGV("requestReopenDevices() called");
1878
1879 AutoMutex _l(mLock);
1880 mNeedToReopenDevices = true;
1881}
1882
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001883void EventHub::dump(std::string& dump) {
1884 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001885
1886 { // acquire lock
1887 AutoMutex _l(mLock);
1888
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001889 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001890
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001891 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892
1893 for (size_t i = 0; i < mDevices.size(); i++) {
1894 const Device* device = mDevices.valueAt(i);
1895 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001896 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001897 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001898 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001899 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001900 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001903 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001904 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001905 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1906 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001908 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001909 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001910 "product=0x%04x, version=0x%04x\n",
1911 device->identifier.bus, device->identifier.vendor,
1912 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001913 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001914 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001915 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001916 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001917 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001918 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001919 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001920 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001921 dump += INDENT3 "VideoDevice: ";
1922 if (device->videoDevice) {
1923 dump += device->videoDevice->dump() + "\n";
1924 } else {
1925 dump += "<none>\n";
1926 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001927 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001928
1929 dump += INDENT "Unattached video devices:\n";
1930 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1931 dump += INDENT2 + videoDevice->dump() + "\n";
1932 }
1933 if (mUnattachedVideoDevices.empty()) {
1934 dump += INDENT2 "<none>\n";
1935 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001936 } // release lock
1937}
1938
1939void EventHub::monitor() {
1940 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1941 mLock.lock();
1942 mLock.unlock();
1943}
1944
1945
1946}; // namespace android