blob: af023148ccd8b9a83f37f33f165f0b31495aeef9 [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 <unistd.h>
32
Michael Wrightd02c5b62014-02-10 15:10:22 -080033#define LOG_TAG "EventHub"
34
35// #define LOG_NDEBUG 0
36
37#include "EventHub.h"
38
39#include <hardware_legacy/power.h>
40
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080041#include <android-base/stringprintf.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.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
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080096/**
97 * Return true if name matches "v4l-touch*"
98 */
99static bool isV4lTouchNode(const char* name) {
100 return strstr(name, "v4l-touch") == name;
101}
102
Philip Quinn39b81682019-01-09 22:20:39 -0800103/**
104 * Returns true if V4L devices should be scanned.
105 *
106 * The system property ro.input.video_enabled can be used to control whether
107 * EventHub scans and opens V4L devices. As V4L does not support multiple
108 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700109 * them.
110 *
111 * Setting this to "false" would prevent any video devices from being discovered and
112 * associated with input devices.
113 *
114 * This property can be used as follows:
115 * 1. To turn off features that are dependent on video device presence.
116 * 2. During testing and development, to allow other clients to read video devices
117 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800118 */
119static bool isV4lScanningEnabled() {
120 return property_get_bool("ro.input.video_enabled", true /* default_value */);
121}
122
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800123static nsecs_t processEventTimestamp(const struct input_event& event) {
124 // Use the time specified in the event instead of the current time
125 // so that downstream code can get more accurate estimates of
126 // event dispatch latency from the time the event is enqueued onto
127 // the evdev client buffer.
128 //
129 // The event's timestamp fortuitously uses the same monotonic clock
130 // time base as the rest of Android. The kernel event device driver
131 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
132 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
133 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
134 // system call that also queries ktime_get_ts().
135
136 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
137 microseconds_to_nanoseconds(event.time.tv_usec);
138 return inputEventTime;
139}
140
Michael Wrightd02c5b62014-02-10 15:10:22 -0800141// --- Global Functions ---
142
143uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
144 // Touch devices get dibs on touch-related axes.
145 if (deviceClasses & INPUT_DEVICE_CLASS_TOUCH) {
146 switch (axis) {
147 case ABS_X:
148 case ABS_Y:
149 case ABS_PRESSURE:
150 case ABS_TOOL_WIDTH:
151 case ABS_DISTANCE:
152 case ABS_TILT_X:
153 case ABS_TILT_Y:
154 case ABS_MT_SLOT:
155 case ABS_MT_TOUCH_MAJOR:
156 case ABS_MT_TOUCH_MINOR:
157 case ABS_MT_WIDTH_MAJOR:
158 case ABS_MT_WIDTH_MINOR:
159 case ABS_MT_ORIENTATION:
160 case ABS_MT_POSITION_X:
161 case ABS_MT_POSITION_Y:
162 case ABS_MT_TOOL_TYPE:
163 case ABS_MT_BLOB_ID:
164 case ABS_MT_TRACKING_ID:
165 case ABS_MT_PRESSURE:
166 case ABS_MT_DISTANCE:
167 return INPUT_DEVICE_CLASS_TOUCH;
168 }
169 }
170
Michael Wright842500e2015-03-13 17:32:02 -0700171 // External stylus gets the pressure axis
172 if (deviceClasses & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
173 if (axis == ABS_PRESSURE) {
174 return INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
175 }
176 }
177
Michael Wrightd02c5b62014-02-10 15:10:22 -0800178 // Joystick devices get the rest.
179 return deviceClasses & INPUT_DEVICE_CLASS_JOYSTICK;
180}
181
182// --- EventHub::Device ---
183
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800185 const InputDeviceIdentifier& identifier) :
Yi Kong9b14ac62018-07-17 13:48:38 -0700186 next(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 fd(fd), id(id), path(path), identifier(identifier),
Yi Kong9b14ac62018-07-17 13:48:38 -0700188 classes(0), configuration(nullptr), virtualKeyMap(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800189 ffEffectPlaying(false), ffEffectId(-1), controllerNumber(0),
Siarhei Vishniakou88786812018-11-09 15:36:21 -0800190 enabled(true), isVirtual(fd < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191 memset(keyBitmask, 0, sizeof(keyBitmask));
192 memset(absBitmask, 0, sizeof(absBitmask));
193 memset(relBitmask, 0, sizeof(relBitmask));
194 memset(swBitmask, 0, sizeof(swBitmask));
195 memset(ledBitmask, 0, sizeof(ledBitmask));
196 memset(ffBitmask, 0, sizeof(ffBitmask));
197 memset(propBitmask, 0, sizeof(propBitmask));
198}
199
200EventHub::Device::~Device() {
201 close();
202 delete configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800203}
204
205void EventHub::Device::close() {
206 if (fd >= 0) {
207 ::close(fd);
208 fd = -1;
209 }
210}
211
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700212status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100213 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700214 if(fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100215 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700216 return -errno;
217 }
218 enabled = true;
219 return OK;
220}
221
222status_t EventHub::Device::disable() {
223 close();
224 enabled = false;
225 return OK;
226}
227
228bool EventHub::Device::hasValidFd() {
229 return !isVirtual && enabled;
230}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800231
232// --- EventHub ---
233
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234const int EventHub::EPOLL_MAX_EVENTS;
235
236EventHub::EventHub(void) :
237 mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD), mNextDeviceId(1), mControllerNumbers(),
Yi Kong9b14ac62018-07-17 13:48:38 -0700238 mOpeningDevices(nullptr), mClosingDevices(nullptr),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800239 mNeedToSendFinishedDeviceScan(false),
240 mNeedToReopenDevices(false), mNeedToScanDevices(true),
241 mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
242 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
243
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800244 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800245 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800246
247 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800248 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
249 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
250 DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800251 if (isV4lScanningEnabled()) {
252 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
253 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
254 VIDEO_DEVICE_PATH, strerror(errno));
255 } else {
256 mVideoWd = -1;
257 ALOGI("Video device scanning disabled");
258 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800259
260 struct epoll_event eventItem;
261 memset(&eventItem, 0, sizeof(eventItem));
262 eventItem.events = EPOLLIN;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700263 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800264 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
266
267 int wakeFds[2];
268 result = pipe(wakeFds);
269 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
270
271 mWakeReadPipeFd = wakeFds[0];
272 mWakeWritePipeFd = wakeFds[1];
273
274 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
275 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
276 errno);
277
278 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
279 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
280 errno);
281
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700282 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800283 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
284 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
285 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800286}
287
288EventHub::~EventHub(void) {
289 closeAllDevicesLocked();
290
291 while (mClosingDevices) {
292 Device* device = mClosingDevices;
293 mClosingDevices = device->next;
294 delete device;
295 }
296
297 ::close(mEpollFd);
298 ::close(mINotifyFd);
299 ::close(mWakeReadPipeFd);
300 ::close(mWakeWritePipeFd);
301
302 release_wake_lock(WAKE_LOCK_ID);
303}
304
305InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
306 AutoMutex _l(mLock);
307 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700308 if (device == nullptr) return InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800309 return device->identifier;
310}
311
312uint32_t EventHub::getDeviceClasses(int32_t deviceId) const {
313 AutoMutex _l(mLock);
314 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700315 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800316 return device->classes;
317}
318
319int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
320 AutoMutex _l(mLock);
321 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -0700322 if (device == nullptr) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800323 return device->controllerNumber;
324}
325
326void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
327 AutoMutex _l(mLock);
328 Device* device = getDeviceLocked(deviceId);
329 if (device && device->configuration) {
330 *outConfiguration = *device->configuration;
331 } else {
332 outConfiguration->clear();
333 }
334}
335
336status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
337 RawAbsoluteAxisInfo* outAxisInfo) const {
338 outAxisInfo->clear();
339
340 if (axis >= 0 && axis <= ABS_MAX) {
341 AutoMutex _l(mLock);
342
343 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700344 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800345 struct input_absinfo info;
346 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
347 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100348 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800349 return -errno;
350 }
351
352 if (info.minimum != info.maximum) {
353 outAxisInfo->valid = true;
354 outAxisInfo->minValue = info.minimum;
355 outAxisInfo->maxValue = info.maximum;
356 outAxisInfo->flat = info.flat;
357 outAxisInfo->fuzz = info.fuzz;
358 outAxisInfo->resolution = info.resolution;
359 }
360 return OK;
361 }
362 }
363 return -1;
364}
365
366bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
367 if (axis >= 0 && axis <= REL_MAX) {
368 AutoMutex _l(mLock);
369
370 Device* device = getDeviceLocked(deviceId);
371 if (device) {
372 return test_bit(axis, device->relBitmask);
373 }
374 }
375 return false;
376}
377
378bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
379 if (property >= 0 && property <= INPUT_PROP_MAX) {
380 AutoMutex _l(mLock);
381
382 Device* device = getDeviceLocked(deviceId);
383 if (device) {
384 return test_bit(property, device->propBitmask);
385 }
386 }
387 return false;
388}
389
390int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
391 if (scanCode >= 0 && scanCode <= KEY_MAX) {
392 AutoMutex _l(mLock);
393
394 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700395 if (device && device->hasValidFd() && test_bit(scanCode, device->keyBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800396 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
397 memset(keyState, 0, sizeof(keyState));
398 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
399 return test_bit(scanCode, keyState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
400 }
401 }
402 }
403 return AKEY_STATE_UNKNOWN;
404}
405
406int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
407 AutoMutex _l(mLock);
408
409 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700410 if (device && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800411 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
413 if (scanCodes.size() != 0) {
414 uint8_t keyState[sizeof_bit_array(KEY_MAX + 1)];
415 memset(keyState, 0, sizeof(keyState));
416 if (ioctl(device->fd, EVIOCGKEY(sizeof(keyState)), keyState) >= 0) {
417 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800418 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800419 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, keyState)) {
420 return AKEY_STATE_DOWN;
421 }
422 }
423 return AKEY_STATE_UP;
424 }
425 }
426 }
427 return AKEY_STATE_UNKNOWN;
428}
429
430int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
431 if (sw >= 0 && sw <= SW_MAX) {
432 AutoMutex _l(mLock);
433
434 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700435 if (device && device->hasValidFd() && test_bit(sw, device->swBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436 uint8_t swState[sizeof_bit_array(SW_MAX + 1)];
437 memset(swState, 0, sizeof(swState));
438 if (ioctl(device->fd, EVIOCGSW(sizeof(swState)), swState) >= 0) {
439 return test_bit(sw, swState) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
440 }
441 }
442 }
443 return AKEY_STATE_UNKNOWN;
444}
445
446status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
447 *outValue = 0;
448
449 if (axis >= 0 && axis <= ABS_MAX) {
450 AutoMutex _l(mLock);
451
452 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700453 if (device && device->hasValidFd() && test_bit(axis, device->absBitmask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454 struct input_absinfo info;
455 if(ioctl(device->fd, EVIOCGABS(axis), &info)) {
456 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100457 axis, device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 return -errno;
459 }
460
461 *outValue = info.value;
462 return OK;
463 }
464 }
465 return -1;
466}
467
468bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes,
469 const int32_t* keyCodes, uint8_t* outFlags) const {
470 AutoMutex _l(mLock);
471
472 Device* device = getDeviceLocked(deviceId);
473 if (device && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800474 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800475 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
476 scanCodes.clear();
477
478 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(
479 keyCodes[codeIndex], &scanCodes);
480 if (! err) {
481 // check the possible scan codes identified by the layout map against the
482 // map of codes actually emitted by the driver
483 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
484 if (test_bit(scanCodes[sc], device->keyBitmask)) {
485 outFlags[codeIndex] = 1;
486 break;
487 }
488 }
489 }
490 }
491 return true;
492 }
493 return false;
494}
495
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700496status_t EventHub::mapKey(int32_t deviceId,
497 int32_t scanCode, int32_t usageCode, int32_t metaState,
498 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 AutoMutex _l(mLock);
500 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700501 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502
503 if (device) {
504 // Check the key character map first.
505 sp<KeyCharacterMap> kcm = device->getKeyCharacterMap();
Yi Kong9b14ac62018-07-17 13:48:38 -0700506 if (kcm != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800507 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
508 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700509 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 }
511 }
512
513 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700514 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800515 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700516 status = NO_ERROR;
517 }
518 }
519
520 if (status == NO_ERROR) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700521 if (kcm != nullptr) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700522 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
523 } else {
524 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525 }
526 }
527 }
528
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700529 if (status != NO_ERROR) {
530 *outKeycode = 0;
531 *outFlags = 0;
532 *outMetaState = metaState;
533 }
534
535 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536}
537
538status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
539 AutoMutex _l(mLock);
540 Device* device = getDeviceLocked(deviceId);
541
542 if (device && device->keyMap.haveKeyLayout()) {
543 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
544 if (err == NO_ERROR) {
545 return NO_ERROR;
546 }
547 }
548
549 return NAME_NOT_FOUND;
550}
551
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100552void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800553 AutoMutex _l(mLock);
554
555 mExcludedDevices = devices;
556}
557
558bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
559 AutoMutex _l(mLock);
560 Device* device = getDeviceLocked(deviceId);
561 if (device && scanCode >= 0 && scanCode <= KEY_MAX) {
562 if (test_bit(scanCode, device->keyBitmask)) {
563 return true;
564 }
565 }
566 return false;
567}
568
569bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
570 AutoMutex _l(mLock);
571 Device* device = getDeviceLocked(deviceId);
572 int32_t sc;
573 if (device && mapLed(device, led, &sc) == NO_ERROR) {
574 if (test_bit(sc, device->ledBitmask)) {
575 return true;
576 }
577 }
578 return false;
579}
580
581void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
582 AutoMutex _l(mLock);
583 Device* device = getDeviceLocked(deviceId);
584 setLedStateLocked(device, led, on);
585}
586
587void EventHub::setLedStateLocked(Device* device, int32_t led, bool on) {
588 int32_t sc;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700589 if (device && device->hasValidFd() && mapLed(device, led, &sc) != NAME_NOT_FOUND) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800590 struct input_event ev;
591 ev.time.tv_sec = 0;
592 ev.time.tv_usec = 0;
593 ev.type = EV_LED;
594 ev.code = sc;
595 ev.value = on ? 1 : 0;
596
597 ssize_t nWrite;
598 do {
599 nWrite = write(device->fd, &ev, sizeof(struct input_event));
600 } while (nWrite == -1 && errno == EINTR);
601 }
602}
603
604void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800605 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 outVirtualKeys.clear();
607
608 AutoMutex _l(mLock);
609 Device* device = getDeviceLocked(deviceId);
610 if (device && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800611 const std::vector<VirtualKeyDefinition> virtualKeys =
612 device->virtualKeyMap->getVirtualKeys();
613 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 }
615}
616
617sp<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
618 AutoMutex _l(mLock);
619 Device* device = getDeviceLocked(deviceId);
620 if (device) {
621 return device->getKeyCharacterMap();
622 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700623 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624}
625
626bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId,
627 const sp<KeyCharacterMap>& map) {
628 AutoMutex _l(mLock);
629 Device* device = getDeviceLocked(deviceId);
630 if (device) {
631 if (map != device->overlayKeyMap) {
632 device->overlayKeyMap = map;
633 device->combinedKeyMap = KeyCharacterMap::combine(
634 device->keyMap.keyCharacterMap, map);
635 return true;
636 }
637 }
638 return false;
639}
640
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100641static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
642 std::string rawDescriptor;
643 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 identifier.product);
645 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100646 if (!identifier.uniqueId.empty()) {
647 rawDescriptor += "uniqueId:";
648 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100650 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 }
652
653 if (identifier.vendor == 0 && identifier.product == 0) {
654 // If we don't know the vendor and product id, then the device is probably
655 // built-in so we need to rely on other information to uniquely identify
656 // the input device. Usually we try to avoid relying on the device name or
657 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100658 if (!identifier.name.empty()) {
659 rawDescriptor += "name:";
660 rawDescriptor += identifier.name;
661 } else if (!identifier.location.empty()) {
662 rawDescriptor += "location:";
663 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 }
665 }
666 identifier.descriptor = sha1(rawDescriptor);
667 return rawDescriptor;
668}
669
670void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
671 // Compute a device descriptor that uniquely identifies the device.
672 // The descriptor is assumed to be a stable identifier. Its value should not
673 // change between reboots, reconnections, firmware updates or new releases
674 // of Android. In practice we sometimes get devices that cannot be uniquely
675 // identified. In this case we enforce uniqueness between connected devices.
676 // Ideally, we also want the descriptor to be short and relatively opaque.
677
678 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100679 std::string rawDescriptor = generateDescriptor(identifier);
680 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681 // If it didn't have a unique id check for conflicts and enforce
682 // uniqueness if necessary.
Yi Kong9b14ac62018-07-17 13:48:38 -0700683 while(getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 identifier.nonce++;
685 rawDescriptor = generateDescriptor(identifier);
686 }
687 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100688 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
689 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690}
691
692void EventHub::vibrate(int32_t deviceId, nsecs_t duration) {
693 AutoMutex _l(mLock);
694 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700695 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 ff_effect effect;
697 memset(&effect, 0, sizeof(effect));
698 effect.type = FF_RUMBLE;
699 effect.id = device->ffEffectId;
700 effect.u.rumble.strong_magnitude = 0xc000;
701 effect.u.rumble.weak_magnitude = 0xc000;
702 effect.replay.length = (duration + 999999LL) / 1000000LL;
703 effect.replay.delay = 0;
704 if (ioctl(device->fd, EVIOCSFF, &effect)) {
705 ALOGW("Could not upload force feedback effect to 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->ffEffectId = effect.id;
710
711 struct input_event ev;
712 ev.time.tv_sec = 0;
713 ev.time.tv_usec = 0;
714 ev.type = EV_FF;
715 ev.code = device->ffEffectId;
716 ev.value = 1;
717 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
718 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100719 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 return;
721 }
722 device->ffEffectPlaying = true;
723 }
724}
725
726void EventHub::cancelVibrate(int32_t deviceId) {
727 AutoMutex _l(mLock);
728 Device* device = getDeviceLocked(deviceId);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700729 if (device && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800730 if (device->ffEffectPlaying) {
731 device->ffEffectPlaying = false;
732
733 struct input_event ev;
734 ev.time.tv_sec = 0;
735 ev.time.tv_usec = 0;
736 ev.type = EV_FF;
737 ev.code = device->ffEffectId;
738 ev.value = 0;
739 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
740 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100741 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 return;
743 }
744 }
745 }
746}
747
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100748EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800749 size_t size = mDevices.size();
750 for (size_t i = 0; i < size; i++) {
751 Device* device = mDevices.valueAt(i);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100752 if (descriptor == device->identifier.descriptor) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 return device;
754 }
755 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700756 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757}
758
759EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800760 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800761 deviceId = mBuiltInKeyboardId;
762 }
763 ssize_t index = mDevices.indexOfKey(deviceId);
764 return index >= 0 ? mDevices.valueAt(index) : NULL;
765}
766
767EventHub::Device* EventHub::getDeviceByPathLocked(const char* devicePath) const {
768 for (size_t i = 0; i < mDevices.size(); i++) {
769 Device* device = mDevices.valueAt(i);
770 if (device->path == devicePath) {
771 return device;
772 }
773 }
Yi Kong9b14ac62018-07-17 13:48:38 -0700774 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775}
776
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700777/**
778 * The file descriptor could be either input device, or a video device (associated with a
779 * specific input device). Check both cases here, and return the device that this event
780 * belongs to. Caller can compare the fd's once more to determine event type.
781 * Looks through all input devices, and only attached video devices. Unattached video
782 * devices are ignored.
783 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700784EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
785 for (size_t i = 0; i < mDevices.size(); i++) {
786 Device* device = mDevices.valueAt(i);
787 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700788 // This is an input device event
789 return device;
790 }
791 if (device->videoDevice && device->videoDevice->getFd() == fd) {
792 // This is a video device event
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700793 return device;
794 }
795 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700796 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
797 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700798 return nullptr;
799}
800
Michael Wrightd02c5b62014-02-10 15:10:22 -0800801size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
802 ALOG_ASSERT(bufferSize >= 1);
803
804 AutoMutex _l(mLock);
805
806 struct input_event readBuffer[bufferSize];
807
808 RawEvent* event = buffer;
809 size_t capacity = bufferSize;
810 bool awoken = false;
811 for (;;) {
812 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
813
814 // Reopen input devices if needed.
815 if (mNeedToReopenDevices) {
816 mNeedToReopenDevices = false;
817
818 ALOGI("Reopening all input devices due to a configuration change.");
819
820 closeAllDevicesLocked();
821 mNeedToScanDevices = true;
822 break; // return to the caller before we actually rescan
823 }
824
825 // Report any devices that had last been added/removed.
826 while (mClosingDevices) {
827 Device* device = mClosingDevices;
828 ALOGV("Reporting device closed: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100829 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 mClosingDevices = device->next;
831 event->when = now;
Prabir Pradhancae4b3a2019-02-05 18:51:32 -0800832 event->deviceId = (device->id == mBuiltInKeyboardId) ?
833 ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834 event->type = DEVICE_REMOVED;
835 event += 1;
836 delete device;
837 mNeedToSendFinishedDeviceScan = true;
838 if (--capacity == 0) {
839 break;
840 }
841 }
842
843 if (mNeedToScanDevices) {
844 mNeedToScanDevices = false;
845 scanDevicesLocked();
846 mNeedToSendFinishedDeviceScan = true;
847 }
848
Yi Kong9b14ac62018-07-17 13:48:38 -0700849 while (mOpeningDevices != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 Device* device = mOpeningDevices;
851 ALOGV("Reporting device opened: id=%d, name=%s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100852 device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 mOpeningDevices = device->next;
854 event->when = now;
855 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
856 event->type = DEVICE_ADDED;
857 event += 1;
858 mNeedToSendFinishedDeviceScan = true;
859 if (--capacity == 0) {
860 break;
861 }
862 }
863
864 if (mNeedToSendFinishedDeviceScan) {
865 mNeedToSendFinishedDeviceScan = false;
866 event->when = now;
867 event->type = FINISHED_DEVICE_SCAN;
868 event += 1;
869 if (--capacity == 0) {
870 break;
871 }
872 }
873
874 // Grab the next input event.
875 bool deviceChanged = false;
876 while (mPendingEventIndex < mPendingEventCount) {
877 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700878 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 if (eventItem.events & EPOLLIN) {
880 mPendingINotify = true;
881 } else {
882 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
883 }
884 continue;
885 }
886
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700887 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 if (eventItem.events & EPOLLIN) {
889 ALOGV("awoken after wake()");
890 awoken = true;
891 char buffer[16];
892 ssize_t nRead;
893 do {
894 nRead = read(mWakeReadPipeFd, buffer, sizeof(buffer));
895 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(buffer));
896 } else {
897 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
898 eventItem.events);
899 }
900 continue;
901 }
902
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700903 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700904 if (!device) {
905 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.",
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700906 eventItem.events, eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700907 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 continue;
909 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -0700910 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
911 if (eventItem.events & EPOLLIN) {
912 size_t numFrames = device->videoDevice->readAndQueueFrames();
913 if (numFrames == 0) {
914 ALOGE("Received epoll event for video device %s, but could not read frame",
915 device->videoDevice->getName().c_str());
916 }
917 } else if (eventItem.events & EPOLLHUP) {
918 // TODO(b/121395353) - consider adding EPOLLRDHUP
919 ALOGI("Removing video device %s due to epoll hang-up event.",
920 device->videoDevice->getName().c_str());
921 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
922 device->videoDevice = nullptr;
923 } else {
924 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
925 eventItem.events, device->videoDevice->getName().c_str());
926 ALOG_ASSERT(!DEBUG);
927 }
928 continue;
929 }
930 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -0800931 if (eventItem.events & EPOLLIN) {
932 int32_t readSize = read(device->fd, readBuffer,
933 sizeof(struct input_event) * capacity);
934 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
935 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -0700936 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
937 " bufferSize: %zu capacity: %zu errno: %d)\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800938 device->fd, readSize, bufferSize, capacity, errno);
939 deviceChanged = true;
940 closeDeviceLocked(device);
941 } else if (readSize < 0) {
942 if (errno != EAGAIN && errno != EINTR) {
943 ALOGW("could not get event (errno=%d)", errno);
944 }
945 } else if ((readSize % sizeof(struct input_event)) != 0) {
946 ALOGE("could not get event (wrong size: %d)", readSize);
947 } else {
948 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
949
950 size_t count = size_t(readSize) / sizeof(struct input_event);
951 for (size_t i = 0; i < count; i++) {
952 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800953 event->when = processEventTimestamp(iev);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954 event->deviceId = deviceId;
955 event->type = iev.type;
956 event->code = iev.code;
957 event->value = iev.value;
958 event += 1;
959 capacity -= 1;
960 }
961 if (capacity == 0) {
962 // The result buffer is full. Reset the pending event index
963 // so we will try to read the device again on the next iteration.
964 mPendingEventIndex -= 1;
965 break;
966 }
967 }
968 } else if (eventItem.events & EPOLLHUP) {
969 ALOGI("Removing device %s due to epoll hang-up event.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100970 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971 deviceChanged = true;
972 closeDeviceLocked(device);
973 } else {
974 ALOGW("Received unexpected epoll event 0x%08x for device %s.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100975 eventItem.events, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976 }
977 }
978
979 // readNotify() will modify the list of devices so this must be done after
980 // processing all other events to ensure that we read all remaining events
981 // before closing the devices.
982 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
983 mPendingINotify = false;
984 readNotifyLocked();
985 deviceChanged = true;
986 }
987
988 // Report added or removed devices immediately.
989 if (deviceChanged) {
990 continue;
991 }
992
993 // Return now if we have collected any events or if we were explicitly awoken.
994 if (event != buffer || awoken) {
995 break;
996 }
997
998 // Poll for events. Mind the wake lock dance!
999 // We hold a wake lock at all times except during epoll_wait(). This works due to some
1000 // subtle choreography. When a device driver has pending (unread) events, it acquires
1001 // a kernel wake lock. However, once the last pending event has been read, the device
1002 // driver will release the kernel wake lock. To prevent the system from going to sleep
1003 // when this happens, the EventHub holds onto its own user wake lock while the client
1004 // is processing events. Thus the system can only sleep if there are no events
1005 // pending or currently being processed.
1006 //
1007 // The timeout is advisory only. If the device is asleep, it will not wake just to
1008 // service the timeout.
1009 mPendingEventIndex = 0;
1010
1011 mLock.unlock(); // release lock before poll, must be before release_wake_lock
1012 release_wake_lock(WAKE_LOCK_ID);
1013
1014 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1015
1016 acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
1017 mLock.lock(); // reacquire lock after poll, must be after acquire_wake_lock
1018
1019 if (pollResult == 0) {
1020 // Timed out.
1021 mPendingEventCount = 0;
1022 break;
1023 }
1024
1025 if (pollResult < 0) {
1026 // An error occurred.
1027 mPendingEventCount = 0;
1028
1029 // Sleep after errors to avoid locking up the system.
1030 // Hopefully the error is transient.
1031 if (errno != EINTR) {
1032 ALOGW("poll failed (errno=%d)\n", errno);
1033 usleep(100000);
1034 }
1035 } else {
1036 // Some events occurred.
1037 mPendingEventCount = size_t(pollResult);
1038 }
1039 }
1040
1041 // All done, return the number of events we read.
1042 return event - buffer;
1043}
1044
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001045std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
1046 AutoMutex _l(mLock);
1047
1048 Device* device = getDeviceLocked(deviceId);
1049 if (!device || !device->videoDevice) {
1050 return {};
1051 }
1052 return device->videoDevice->consumeFrames();
1053}
1054
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055void EventHub::wake() {
1056 ALOGV("wake() called");
1057
1058 ssize_t nWrite;
1059 do {
1060 nWrite = write(mWakeWritePipeFd, "W", 1);
1061 } while (nWrite == -1 && errno == EINTR);
1062
1063 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001064 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065 }
1066}
1067
1068void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001069 status_t result = scanDirLocked(DEVICE_PATH);
1070 if(result < 0) {
1071 ALOGE("scan dir failed for %s", DEVICE_PATH);
1072 }
Philip Quinn39b81682019-01-09 22:20:39 -08001073 if (isV4lScanningEnabled()) {
1074 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1075 if (result != OK) {
1076 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1077 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001078 }
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001079 if (mDevices.indexOfKey(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) < 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 createVirtualKeyboardLocked();
1081 }
1082}
1083
1084// ----------------------------------------------------------------------------
1085
1086static bool containsNonZeroByte(const uint8_t* array, uint32_t startIndex, uint32_t endIndex) {
1087 const uint8_t* end = array + endIndex;
1088 array += startIndex;
1089 while (array != end) {
1090 if (*(array++) != 0) {
1091 return true;
1092 }
1093 }
1094 return false;
1095}
1096
1097static const int32_t GAMEPAD_KEYCODES[] = {
1098 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C,
1099 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z,
1100 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1,
1101 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2,
1102 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR,
1103 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104};
1105
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001106status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001107 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001108 struct epoll_event eventItem = {};
1109 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1110 eventItem.data.fd = fd;
1111 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1112 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001113 return -errno;
1114 }
1115 return OK;
1116}
1117
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001118status_t EventHub::unregisterFdFromEpoll(int fd) {
1119 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1120 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1121 return -errno;
1122 }
1123 return OK;
1124}
1125
1126status_t EventHub::registerDeviceForEpollLocked(Device* device) {
1127 if (device == nullptr) {
1128 if (DEBUG) {
1129 LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
1130 }
1131 return BAD_VALUE;
1132 }
1133 status_t result = registerFdForEpoll(device->fd);
1134 if (result != OK) {
1135 ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001136 return result;
1137 }
1138 if (device->videoDevice) {
1139 registerVideoDeviceForEpollLocked(*device->videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001140 }
1141 return result;
1142}
1143
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001144void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1145 status_t result = registerFdForEpoll(videoDevice.getFd());
1146 if (result != OK) {
1147 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1148 }
1149}
1150
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001151status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
1152 if (device->hasValidFd()) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001153 status_t result = unregisterFdFromEpoll(device->fd);
1154 if (result != OK) {
1155 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
1156 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001157 }
1158 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001159 if (device->videoDevice) {
1160 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1161 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001162 return OK;
1163}
1164
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001165void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1166 if (videoDevice.hasValidFd()) {
1167 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1168 if (result != OK) {
1169 ALOGW("Could not remove video device fd from epoll for device: %s",
1170 videoDevice.getName().c_str());
1171 }
1172 }
1173}
1174
1175status_t EventHub::openDeviceLocked(const char* devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001176 char buffer[80];
1177
1178 ALOGV("Opening device: %s", devicePath);
1179
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001180 int fd = open(devicePath, O_RDWR | O_CLOEXEC | O_NONBLOCK);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 if(fd < 0) {
1182 ALOGE("could not open %s, %s\n", devicePath, strerror(errno));
1183 return -1;
1184 }
1185
1186 InputDeviceIdentifier identifier;
1187
1188 // Get device name.
1189 if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001190 ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 } else {
1192 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001193 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 }
1195
1196 // Check to see if the device is on our excluded list
1197 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001198 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001199 if (identifier.name == item) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001200 ALOGI("ignoring event id %s driver %s\n", devicePath, item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 close(fd);
1202 return -1;
1203 }
1204 }
1205
1206 // Get device driver version.
1207 int driverVersion;
1208 if(ioctl(fd, EVIOCGVERSION, &driverVersion)) {
1209 ALOGE("could not get driver version for %s, %s\n", devicePath, strerror(errno));
1210 close(fd);
1211 return -1;
1212 }
1213
1214 // Get device identifier.
1215 struct input_id inputId;
1216 if(ioctl(fd, EVIOCGID, &inputId)) {
1217 ALOGE("could not get device input id for %s, %s\n", devicePath, strerror(errno));
1218 close(fd);
1219 return -1;
1220 }
1221 identifier.bus = inputId.bustype;
1222 identifier.product = inputId.product;
1223 identifier.vendor = inputId.vendor;
1224 identifier.version = inputId.version;
1225
1226 // Get device physical location.
1227 if(ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1228 //fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
1229 } else {
1230 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001231 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233
1234 // Get device unique id.
1235 if(ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1236 //fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
1237 } else {
1238 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001239 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 }
1241
1242 // Fill in the descriptor.
1243 assignDescriptorLocked(identifier);
1244
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 // Allocate device. (The device object takes ownership of the fd at this point.)
1246 int32_t deviceId = mNextDeviceId++;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001247 Device* device = new Device(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248
1249 ALOGV("add device %d: %s\n", deviceId, devicePath);
1250 ALOGV(" bus: %04x\n"
1251 " vendor %04x\n"
1252 " product %04x\n"
1253 " version %04x\n",
1254 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001255 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1256 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1257 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1258 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001259 ALOGV(" driver: v%d.%d.%d\n",
1260 driverVersion >> 16, (driverVersion >> 8) & 0xff, driverVersion & 0xff);
1261
1262 // Load the configuration file for the device.
1263 loadConfigurationLocked(device);
1264
1265 // Figure out the kinds of events the device reports.
1266 ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(device->keyBitmask)), device->keyBitmask);
1267 ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(device->absBitmask)), device->absBitmask);
1268 ioctl(fd, EVIOCGBIT(EV_REL, sizeof(device->relBitmask)), device->relBitmask);
1269 ioctl(fd, EVIOCGBIT(EV_SW, sizeof(device->swBitmask)), device->swBitmask);
1270 ioctl(fd, EVIOCGBIT(EV_LED, sizeof(device->ledBitmask)), device->ledBitmask);
1271 ioctl(fd, EVIOCGBIT(EV_FF, sizeof(device->ffBitmask)), device->ffBitmask);
1272 ioctl(fd, EVIOCGPROP(sizeof(device->propBitmask)), device->propBitmask);
1273
1274 // See if this is a keyboard. Ignore everything in the button range except for
1275 // joystick and gamepad buttons which are handled like keyboards for the most part.
1276 bool haveKeyboardKeys = containsNonZeroByte(device->keyBitmask, 0, sizeof_bit_array(BTN_MISC))
1277 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(KEY_OK),
1278 sizeof_bit_array(KEY_MAX + 1));
1279 bool haveGamepadButtons = containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_MISC),
1280 sizeof_bit_array(BTN_MOUSE))
1281 || containsNonZeroByte(device->keyBitmask, sizeof_bit_array(BTN_JOYSTICK),
1282 sizeof_bit_array(BTN_DIGI));
1283 if (haveKeyboardKeys || haveGamepadButtons) {
1284 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1285 }
1286
1287 // See if this is a cursor device such as a trackball or mouse.
1288 if (test_bit(BTN_MOUSE, device->keyBitmask)
1289 && test_bit(REL_X, device->relBitmask)
1290 && test_bit(REL_Y, device->relBitmask)) {
1291 device->classes |= INPUT_DEVICE_CLASS_CURSOR;
1292 }
1293
Prashant Malani1941ff52015-08-11 18:29:28 -07001294 // See if this is a rotary encoder type device.
1295 String8 deviceType = String8();
1296 if (device->configuration &&
1297 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
1298 if (!deviceType.compare(String8("rotaryEncoder"))) {
1299 device->classes |= INPUT_DEVICE_CLASS_ROTARY_ENCODER;
1300 }
1301 }
1302
Michael Wrightd02c5b62014-02-10 15:10:22 -08001303 // See if this is a touch pad.
1304 // Is this a new modern multi-touch driver?
1305 if (test_bit(ABS_MT_POSITION_X, device->absBitmask)
1306 && test_bit(ABS_MT_POSITION_Y, device->absBitmask)) {
1307 // Some joysticks such as the PS3 controller report axes that conflict
1308 // with the ABS_MT range. Try to confirm that the device really is
1309 // a touch screen.
1310 if (test_bit(BTN_TOUCH, device->keyBitmask) || !haveGamepadButtons) {
1311 device->classes |= INPUT_DEVICE_CLASS_TOUCH | INPUT_DEVICE_CLASS_TOUCH_MT;
1312 }
1313 // Is this an old style single-touch driver?
1314 } else if (test_bit(BTN_TOUCH, device->keyBitmask)
1315 && test_bit(ABS_X, device->absBitmask)
1316 && test_bit(ABS_Y, device->absBitmask)) {
1317 device->classes |= INPUT_DEVICE_CLASS_TOUCH;
Michael Wright842500e2015-03-13 17:32:02 -07001318 // Is this a BT stylus?
1319 } else if ((test_bit(ABS_PRESSURE, device->absBitmask) ||
1320 test_bit(BTN_TOUCH, device->keyBitmask))
1321 && !test_bit(ABS_X, device->absBitmask)
1322 && !test_bit(ABS_Y, device->absBitmask)) {
1323 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL_STYLUS;
1324 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
1325 // can fuse it with the touch screen data, so just take them back. Note this means an
1326 // external stylus cannot also be a keyboard device.
1327 device->classes &= ~INPUT_DEVICE_CLASS_KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001328 }
1329
1330 // See if this device is a joystick.
1331 // Assumes that joysticks always have gamepad buttons in order to distinguish them
1332 // from other devices such as accelerometers that also have absolute axes.
1333 if (haveGamepadButtons) {
1334 uint32_t assumedClasses = device->classes | INPUT_DEVICE_CLASS_JOYSTICK;
1335 for (int i = 0; i <= ABS_MAX; i++) {
1336 if (test_bit(i, device->absBitmask)
1337 && (getAbsAxisUsage(i, assumedClasses) & INPUT_DEVICE_CLASS_JOYSTICK)) {
1338 device->classes = assumedClasses;
1339 break;
1340 }
1341 }
1342 }
1343
1344 // Check whether this device has switches.
1345 for (int i = 0; i <= SW_MAX; i++) {
1346 if (test_bit(i, device->swBitmask)) {
1347 device->classes |= INPUT_DEVICE_CLASS_SWITCH;
1348 break;
1349 }
1350 }
1351
1352 // Check whether this device supports the vibrator.
1353 if (test_bit(FF_RUMBLE, device->ffBitmask)) {
1354 device->classes |= INPUT_DEVICE_CLASS_VIBRATOR;
1355 }
1356
1357 // Configure virtual keys.
1358 if ((device->classes & INPUT_DEVICE_CLASS_TOUCH)) {
1359 // Load the virtual keys for the touch screen, if any.
1360 // We do this now so that we can make sure to load the keymap if necessary.
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001361 bool success = loadVirtualKeyMapLocked(device);
1362 if (success) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;
1364 }
1365 }
1366
1367 // Load the key map.
1368 // We need to do this for joysticks too because the key layout may specify axes.
1369 status_t keyMapStatus = NAME_NOT_FOUND;
1370 if (device->classes & (INPUT_DEVICE_CLASS_KEYBOARD | INPUT_DEVICE_CLASS_JOYSTICK)) {
1371 // Load the keymap for the device.
1372 keyMapStatus = loadKeyMapLocked(device);
1373 }
1374
1375 // Configure the keyboard, gamepad or virtual keyboard.
1376 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1377 // Register the keyboard as a built-in keyboard if it is eligible.
1378 if (!keyMapStatus
1379 && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD
1380 && isEligibleBuiltInKeyboard(device->identifier,
1381 device->configuration, &device->keyMap)) {
1382 mBuiltInKeyboardId = device->id;
1383 }
1384
1385 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
1386 if (hasKeycodeLocked(device, AKEYCODE_Q)) {
1387 device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;
1388 }
1389
1390 // See if this device has a DPAD.
1391 if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&
1392 hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&
1393 hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&
1394 hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&
1395 hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {
1396 device->classes |= INPUT_DEVICE_CLASS_DPAD;
1397 }
1398
1399 // See if this device has a gamepad.
1400 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {
1401 if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {
1402 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;
1403 break;
1404 }
1405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 }
1407
1408 // If the device isn't recognized as something we handle, don't monitor it.
1409 if (device->classes == 0) {
1410 ALOGV("Dropping device: id=%d, path='%s', name='%s'",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001411 deviceId, devicePath, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001412 delete device;
1413 return -1;
1414 }
1415
Tim Kilbourn063ff532015-04-08 10:26:18 -07001416 // Determine whether the device has a mic.
1417 if (deviceHasMicLocked(device)) {
1418 device->classes |= INPUT_DEVICE_CLASS_MIC;
1419 }
1420
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 // Determine whether the device is external or internal.
1422 if (isExternalDeviceLocked(device)) {
1423 device->classes |= INPUT_DEVICE_CLASS_EXTERNAL;
1424 }
1425
Michael Wright42f2c6a2014-03-12 10:33:03 -07001426 if (device->classes & (INPUT_DEVICE_CLASS_JOYSTICK | INPUT_DEVICE_CLASS_DPAD)
1427 && device->classes & INPUT_DEVICE_CLASS_GAMEPAD) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428 device->controllerNumber = getNextControllerNumberLocked(device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001429 setLedForControllerLocked(device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001430 }
1431
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001432 // Find a matching video device by comparing device names
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001433 // This should be done before registerDeviceForEpollLocked, so that both fds are added to epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001434 for (std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1435 if (device->identifier.name == videoDevice->getName()) {
1436 device->videoDevice = std::move(videoDevice);
1437 break;
1438 }
1439 }
1440 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1441 mUnattachedVideoDevices.end(),
1442 [](const std::unique_ptr<TouchVideoDevice>& videoDevice){
1443 return videoDevice == nullptr; }), mUnattachedVideoDevices.end());
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001444
1445 if (registerDeviceForEpollLocked(device) != OK) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 delete device;
1447 return -1;
1448 }
1449
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001450 configureFd(device);
1451
1452 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=0x%x, "
1453 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001454 deviceId, fd, devicePath, device->identifier.name.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001455 device->classes,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001456 device->configurationFile.c_str(),
1457 device->keyMap.keyLayoutFile.c_str(),
1458 device->keyMap.keyCharacterMapFile.c_str(),
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001459 toString(mBuiltInKeyboardId == deviceId));
1460
1461 addDeviceLocked(device);
1462 return OK;
1463}
1464
1465void EventHub::configureFd(Device* device) {
1466 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
1467 if (device->classes & INPUT_DEVICE_CLASS_KEYBOARD) {
1468 // Disable kernel key repeat since we handle it ourselves
1469 unsigned int repeatRate[] = {0, 0};
1470 if (ioctl(device->fd, EVIOCSREP, repeatRate)) {
1471 ALOGW("Unable to disable kernel key repeat for %s: %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001472 device->path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001473 }
1474 }
1475
Michael Wrightd02c5b62014-02-10 15:10:22 -08001476 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
1477 // associated with input events. This is important because the input system
1478 // uses the timestamps extensively and assumes they were recorded using the monotonic
1479 // clock.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480 int clockId = CLOCK_MONOTONIC;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001481 bool usingClockIoctl = !ioctl(device->fd, EVIOCSCLOCKID, &clockId);
Atif Niyaz4180aa42019-05-10 16:27:48 -07001482 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001483}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001484
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001485void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
1486 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
1487 if (!videoDevice) {
1488 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
1489 return;
1490 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001491 // Transfer ownership of this video device to a matching input device
1492 for (size_t i = 0; i < mDevices.size(); i++) {
1493 Device* device = mDevices.valueAt(i);
1494 if (videoDevice->getName() == device->identifier.name) {
1495 device->videoDevice = std::move(videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001496 if (device->enabled) {
1497 registerVideoDeviceForEpollLocked(*device->videoDevice);
1498 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001499 return;
1500 }
1501 }
1502
1503 // Couldn't find a matching input device, so just add it to a temporary holding queue.
1504 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001505 ALOGI("Adding video device %s to list of unattached video devices",
1506 videoDevice->getName().c_str());
1507 mUnattachedVideoDevices.push_back(std::move(videoDevice));
1508}
1509
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001510bool EventHub::isDeviceEnabled(int32_t deviceId) {
1511 AutoMutex _l(mLock);
1512 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001513 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001514 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1515 return false;
1516 }
1517 return device->enabled;
1518}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001519
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001520status_t EventHub::enableDevice(int32_t deviceId) {
1521 AutoMutex _l(mLock);
1522 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001523 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001524 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1525 return BAD_VALUE;
1526 }
1527 if (device->enabled) {
1528 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
1529 return OK;
1530 }
1531 status_t result = device->enable();
1532 if (result != OK) {
1533 ALOGE("Failed to enable device %" PRId32, deviceId);
1534 return result;
1535 }
1536
1537 configureFd(device);
1538
1539 return registerDeviceForEpollLocked(device);
1540}
1541
1542status_t EventHub::disableDevice(int32_t deviceId) {
1543 AutoMutex _l(mLock);
1544 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07001545 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001546 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
1547 return BAD_VALUE;
1548 }
1549 if (!device->enabled) {
1550 ALOGW("Duplicate call to %s, input device already disabled", __func__);
1551 return OK;
1552 }
1553 unregisterDeviceFromEpollLocked(device);
1554 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555}
1556
1557void EventHub::createVirtualKeyboardLocked() {
1558 InputDeviceIdentifier identifier;
1559 identifier.name = "Virtual";
1560 identifier.uniqueId = "<virtual>";
1561 assignDescriptorLocked(identifier);
1562
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001563 Device* device = new Device(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
1564 identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001565 device->classes = INPUT_DEVICE_CLASS_KEYBOARD
1566 | INPUT_DEVICE_CLASS_ALPHAKEY
1567 | INPUT_DEVICE_CLASS_DPAD
1568 | INPUT_DEVICE_CLASS_VIRTUAL;
1569 loadKeyMapLocked(device);
1570 addDeviceLocked(device);
1571}
1572
1573void EventHub::addDeviceLocked(Device* device) {
1574 mDevices.add(device->id, device);
1575 device->next = mOpeningDevices;
1576 mOpeningDevices = device;
1577}
1578
1579void EventHub::loadConfigurationLocked(Device* device) {
1580 device->configurationFile = getInputDeviceConfigurationFilePathByDeviceIdentifier(
1581 device->identifier, INPUT_DEVICE_CONFIGURATION_FILE_TYPE_CONFIGURATION);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001582 if (device->configurationFile.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001583 ALOGD("No input device configuration file found for device '%s'.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001584 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 } else {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001586 status_t status = PropertyMap::load(String8(device->configurationFile.c_str()),
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 &device->configuration);
1588 if (status) {
1589 ALOGE("Error loading input device configuration file for device '%s'. "
1590 "Using default configuration.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001591 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001592 }
1593 }
1594}
1595
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001596bool EventHub::loadVirtualKeyMapLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001597 // The virtual key map is supplied by the kernel as a system board property file.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001598 std::string path;
1599 path += "/sys/board_properties/virtualkeys.";
Siarhei Vishniakoub45635c2019-02-20 19:22:09 -06001600 path += device->identifier.getCanonicalName();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001601 if (access(path.c_str(), R_OK)) {
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001602 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 }
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06001604 device->virtualKeyMap = VirtualKeyMap::load(path);
1605 return device->virtualKeyMap != nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606}
1607
1608status_t EventHub::loadKeyMapLocked(Device* device) {
1609 return device->keyMap.load(device->identifier, device->configuration);
1610}
1611
1612bool EventHub::isExternalDeviceLocked(Device* device) {
1613 if (device->configuration) {
1614 bool value;
1615 if (device->configuration->tryGetProperty(String8("device.internal"), value)) {
1616 return !value;
1617 }
1618 }
1619 return device->identifier.bus == BUS_USB || device->identifier.bus == BUS_BLUETOOTH;
1620}
1621
Tim Kilbourn063ff532015-04-08 10:26:18 -07001622bool EventHub::deviceHasMicLocked(Device* device) {
1623 if (device->configuration) {
1624 bool value;
1625 if (device->configuration->tryGetProperty(String8("audio.mic"), value)) {
1626 return value;
1627 }
1628 }
1629 return false;
1630}
1631
Michael Wrightd02c5b62014-02-10 15:10:22 -08001632int32_t EventHub::getNextControllerNumberLocked(Device* device) {
1633 if (mControllerNumbers.isFull()) {
1634 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001635 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636 return 0;
1637 }
1638 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
1639 // one
1640 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
1641}
1642
1643void EventHub::releaseControllerNumberLocked(Device* device) {
1644 int32_t num = device->controllerNumber;
1645 device->controllerNumber= 0;
1646 if (num == 0) {
1647 return;
1648 }
1649 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
1650}
1651
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001652void EventHub::setLedForControllerLocked(Device* device) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
1654 setLedStateLocked(device, ALED_CONTROLLER_1 + i, device->controllerNumber == i + 1);
1655 }
1656}
1657
1658bool EventHub::hasKeycodeLocked(Device* device, int keycode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001659 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 return false;
1661 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001662
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001663 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001664 device->keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
1665 const size_t N = scanCodes.size();
1666 for (size_t i=0; i<N && i<=KEY_MAX; i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001667 int32_t sc = scanCodes[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001668 if (sc >= 0 && sc <= KEY_MAX && test_bit(sc, device->keyBitmask)) {
1669 return true;
1670 }
1671 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001672
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 return false;
1674}
1675
1676status_t EventHub::mapLed(Device* device, int32_t led, int32_t* outScanCode) const {
Bernhard Rosenkränzer6183eb72014-11-17 21:09:14 +01001677 if (!device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001678 return NAME_NOT_FOUND;
1679 }
1680
1681 int32_t scanCode;
1682 if(device->keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
1683 if(scanCode >= 0 && scanCode <= LED_MAX && test_bit(scanCode, device->ledBitmask)) {
1684 *outScanCode = scanCode;
1685 return NO_ERROR;
1686 }
1687 }
1688 return NAME_NOT_FOUND;
1689}
1690
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001691void EventHub::closeDeviceByPathLocked(const char *devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001692 Device* device = getDeviceByPathLocked(devicePath);
1693 if (device) {
1694 closeDeviceLocked(device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001695 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001696 }
1697 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001698}
1699
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001700/**
1701 * Find the video device by filename, and close it.
1702 * The video device is closed by path during an inotify event, where we don't have the
1703 * additional context about the video device fd, or the associated input device.
1704 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001705void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001706 // A video device may be owned by an existing input device, or it may be stored in
1707 // the mUnattachedVideoDevices queue. Check both locations.
1708 for (size_t i = 0; i < mDevices.size(); i++) {
1709 Device* device = mDevices.valueAt(i);
1710 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001711 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001712 device->videoDevice = nullptr;
1713 return;
1714 }
1715 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001716 mUnattachedVideoDevices.erase(std::remove_if(mUnattachedVideoDevices.begin(),
1717 mUnattachedVideoDevices.end(), [&devicePath](
1718 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
1719 return videoDevice->getPath() == devicePath; }), mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001720}
1721
1722void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001723 mUnattachedVideoDevices.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724 while (mDevices.size() > 0) {
1725 closeDeviceLocked(mDevices.valueAt(mDevices.size() - 1));
1726 }
1727}
1728
1729void EventHub::closeDeviceLocked(Device* device) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001730 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=0x%x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001731 device->path.c_str(), device->identifier.name.c_str(), device->id,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001732 device->fd, device->classes);
1733
1734 if (device->id == mBuiltInKeyboardId) {
1735 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001736 device->path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
1738 }
1739
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001740 unregisterDeviceFromEpollLocked(device);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001741 if (device->videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001742 // This must be done after the video device is removed from epoll
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001743 mUnattachedVideoDevices.push_back(std::move(device->videoDevice));
1744 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001745
1746 releaseControllerNumberLocked(device);
1747
1748 mDevices.removeItem(device->id);
1749 device->close();
1750
1751 // Unlink for opening devices list if it is present.
Yi Kong9b14ac62018-07-17 13:48:38 -07001752 Device* pred = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753 bool found = false;
Yi Kong9b14ac62018-07-17 13:48:38 -07001754 for (Device* entry = mOpeningDevices; entry != nullptr; ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 if (entry == device) {
1756 found = true;
1757 break;
1758 }
1759 pred = entry;
1760 entry = entry->next;
1761 }
1762 if (found) {
1763 // Unlink the device from the opening devices list then delete it.
1764 // We don't need to tell the client that the device was closed because
1765 // it does not even know it was opened in the first place.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001766 ALOGI("Device %s was immediately closed after opening.", device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001767 if (pred) {
1768 pred->next = device->next;
1769 } else {
1770 mOpeningDevices = device->next;
1771 }
1772 delete device;
1773 } else {
1774 // Link into closing devices list.
1775 // The device will be deleted later after we have informed the client.
1776 device->next = mClosingDevices;
1777 mClosingDevices = device;
1778 }
1779}
1780
1781status_t EventHub::readNotifyLocked() {
1782 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 char event_buf[512];
1784 int event_size;
1785 int event_pos = 0;
1786 struct inotify_event *event;
1787
1788 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
1789 res = read(mINotifyFd, event_buf, sizeof(event_buf));
1790 if(res < (int)sizeof(*event)) {
1791 if(errno == EINTR)
1792 return 0;
1793 ALOGW("could not get event, %s\n", strerror(errno));
1794 return -1;
1795 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001796
1797 while(res >= (int)sizeof(*event)) {
1798 event = (struct inotify_event *)(event_buf + event_pos);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001799 if(event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001800 if (event->wd == mInputWd) {
1801 std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
1802 if(event->mask & IN_CREATE) {
1803 openDeviceLocked(filename.c_str());
1804 } else {
1805 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
1806 closeDeviceByPathLocked(filename.c_str());
1807 }
1808 }
1809 else if (event->wd == mVideoWd) {
1810 if (isV4lTouchNode(event->name)) {
1811 std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001812 if (event->mask & IN_CREATE) {
1813 openVideoDeviceLocked(filename);
1814 } else {
1815 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
1816 closeVideoDeviceByPathLocked(filename);
1817 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08001818 }
1819 }
1820 else {
1821 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001822 }
1823 }
1824 event_size = sizeof(*event) + event->len;
1825 res -= event_size;
1826 event_pos += event_size;
1827 }
1828 return 0;
1829}
1830
1831status_t EventHub::scanDirLocked(const char *dirname)
1832{
1833 char devname[PATH_MAX];
1834 char *filename;
1835 DIR *dir;
1836 struct dirent *de;
1837 dir = opendir(dirname);
Yi Kong9b14ac62018-07-17 13:48:38 -07001838 if(dir == nullptr)
Michael Wrightd02c5b62014-02-10 15:10:22 -08001839 return -1;
1840 strcpy(devname, dirname);
1841 filename = devname + strlen(devname);
1842 *filename++ = '/';
1843 while((de = readdir(dir))) {
1844 if(de->d_name[0] == '.' &&
1845 (de->d_name[1] == '\0' ||
1846 (de->d_name[1] == '.' && de->d_name[2] == '\0')))
1847 continue;
1848 strcpy(filename, de->d_name);
1849 openDeviceLocked(devname);
1850 }
1851 closedir(dir);
1852 return 0;
1853}
1854
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001855/**
1856 * Look for all dirname/v4l-touch* devices, and open them.
1857 */
1858status_t EventHub::scanVideoDirLocked(const std::string& dirname)
1859{
1860 DIR* dir;
1861 struct dirent* de;
1862 dir = opendir(dirname.c_str());
1863 if(!dir) {
1864 ALOGE("Could not open video directory %s", dirname.c_str());
1865 return BAD_VALUE;
1866 }
1867
1868 while((de = readdir(dir))) {
1869 const char* name = de->d_name;
1870 if (isV4lTouchNode(name)) {
1871 ALOGI("Found touch video device %s", name);
1872 openVideoDeviceLocked(dirname + "/" + name);
1873 }
1874 }
1875 closedir(dir);
1876 return OK;
1877}
1878
Michael Wrightd02c5b62014-02-10 15:10:22 -08001879void EventHub::requestReopenDevices() {
1880 ALOGV("requestReopenDevices() called");
1881
1882 AutoMutex _l(mLock);
1883 mNeedToReopenDevices = true;
1884}
1885
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001886void EventHub::dump(std::string& dump) {
1887 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888
1889 { // acquire lock
1890 AutoMutex _l(mLock);
1891
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001892 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001894 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895
1896 for (size_t i = 0; i < mDevices.size(); i++) {
1897 const Device* device = mDevices.valueAt(i);
1898 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001899 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001900 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001901 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001903 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001905 dump += StringPrintf(INDENT3 "Classes: 0x%08x\n", device->classes);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001906 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001907 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001908 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
1909 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001910 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001911 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001912 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 "product=0x%04x, version=0x%04x\n",
1914 device->identifier.bus, device->identifier.vendor,
1915 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001916 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001917 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001918 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001919 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001920 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001921 device->configurationFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922 dump += StringPrintf(INDENT3 "HaveKeyboardLayoutOverlay: %s\n",
Yi Kong9b14ac62018-07-17 13:48:38 -07001923 toString(device->overlayKeyMap != nullptr));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08001924 dump += INDENT3 "VideoDevice: ";
1925 if (device->videoDevice) {
1926 dump += device->videoDevice->dump() + "\n";
1927 } else {
1928 dump += "<none>\n";
1929 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001930 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001931
1932 dump += INDENT "Unattached video devices:\n";
1933 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
1934 dump += INDENT2 + videoDevice->dump() + "\n";
1935 }
1936 if (mUnattachedVideoDevices.empty()) {
1937 dump += INDENT2 "<none>\n";
1938 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 } // release lock
1940}
1941
1942void EventHub::monitor() {
1943 // Acquire and release the lock to ensure that the event hub has not deadlocked.
1944 mLock.lock();
1945 mLock.unlock();
1946}
1947
1948
1949}; // namespace android