blob: e3e6c124859fbbc0dc8d03de899dadaeba5d82cc [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>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010027#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070028#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/inotify.h>
30#include <sys/ioctl.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070031#include <sys/limits.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Chris Ye8594e192020-07-14 10:34:06 -070043#include <input/KeyCharacterMap.h>
44#include <input/KeyLayoutMap.h>
45#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070046#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080047#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070048#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080049#include <utils/Log.h>
50#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051
Chris Ye8594e192020-07-14 10:34:06 -070052#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080053#include <regex>
Chris Ye8594e192020-07-14 10:34:06 -070054
55#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080056
Michael Wrightd02c5b62014-02-10 15:10:22 -080057#define INDENT " "
58#define INDENT2 " "
59#define INDENT3 " "
60
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080061using android::base::StringPrintf;
Chris Ye1b0c7342020-07-28 21:57:03 -070062using namespace android::flag_operators;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080063
Michael Wrightd02c5b62014-02-10 15:10:22 -080064namespace android {
65
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070066static const char* DEVICE_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080067// v4l2 devices go directly into /dev
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070068static const char* VIDEO_DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080069
Chris Ye87143712020-11-10 05:05:58 +000070static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
71static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070072
Chris Yee2b1e5c2021-03-10 22:45:12 -080073// Mapping for input battery class node IDs lookup.
74// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
75static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
76 {{"capacity", InputBatteryClass::CAPACITY},
77 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
78 {"status", InputBatteryClass::STATUS}};
79
80// Mapping for input battery class node names lookup.
81// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
82static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
83 {{InputBatteryClass::CAPACITY, "capacity"},
84 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
85 {InputBatteryClass::STATUS, "status"}};
86
Kim Low03ea0352020-11-06 12:45:07 -080087// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
88static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
89 {{"Unknown", BATTERY_STATUS_UNKNOWN},
90 {"Charging", BATTERY_STATUS_CHARGING},
91 {"Discharging", BATTERY_STATUS_DISCHARGING},
92 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
93 {"Full", BATTERY_STATUS_FULL}};
94
95// Mapping taken from
96// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
97static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
98 {"Low", 10},
99 {"Normal", 55},
100 {"High", 70},
101 {"Full", 100},
102 {"Unknown", 50}};
103
Chris Ye3fdbfef2021-01-06 18:45:18 -0800104// Mapping for input led class node names lookup.
105// https://www.kernel.org/doc/html/latest/leds/leds-class.html
106static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
107 {{"red", InputLightClass::RED},
108 {"green", InputLightClass::GREEN},
109 {"blue", InputLightClass::BLUE},
110 {"global", InputLightClass::GLOBAL},
111 {"brightness", InputLightClass::BRIGHTNESS},
112 {"multi_index", InputLightClass::MULTI_INDEX},
113 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
114 {"max_brightness", InputLightClass::MAX_BRIGHTNESS}};
115
116// Mapping for input multicolor led class node names.
117// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
118static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
119 {{InputLightClass::BRIGHTNESS, "brightness"},
120 {InputLightClass::MULTI_INDEX, "multi_index"},
121 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
122
123// Mapping for light color name and the light color
124const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
125 {"green", LightColor::GREEN},
126 {"blue", LightColor::BLUE}};
127
Michael Wrightd02c5b62014-02-10 15:10:22 -0800128static inline const char* toString(bool value) {
129 return value ? "true" : "false";
130}
131
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100132static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700133 SHA_CTX ctx;
134 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100135 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700136 u_char digest[SHA_DIGEST_LENGTH];
137 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800138
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100139 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700140 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800142 }
143 return out;
144}
145
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800146/**
147 * Return true if name matches "v4l-touch*"
148 */
Chris Ye8594e192020-07-14 10:34:06 -0700149static bool isV4lTouchNode(std::string name) {
150 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800151}
152
Philip Quinn39b81682019-01-09 22:20:39 -0800153/**
154 * Returns true if V4L devices should be scanned.
155 *
156 * The system property ro.input.video_enabled can be used to control whether
157 * EventHub scans and opens V4L devices. As V4L does not support multiple
158 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700159 * them.
160 *
161 * Setting this to "false" would prevent any video devices from being discovered and
162 * associated with input devices.
163 *
164 * This property can be used as follows:
165 * 1. To turn off features that are dependent on video device presence.
166 * 2. During testing and development, to allow other clients to read video devices
167 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800168 */
169static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700170 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800171}
172
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800173static nsecs_t processEventTimestamp(const struct input_event& event) {
174 // Use the time specified in the event instead of the current time
175 // so that downstream code can get more accurate estimates of
176 // event dispatch latency from the time the event is enqueued onto
177 // the evdev client buffer.
178 //
179 // The event's timestamp fortuitously uses the same monotonic clock
180 // time base as the rest of Android. The kernel event device driver
181 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
182 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
183 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
184 // system call that also queries ktime_get_ts().
185
186 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.time.tv_sec) +
187 microseconds_to_nanoseconds(event.time.tv_usec);
188 return inputEventTime;
189}
190
Kim Low03ea0352020-11-06 12:45:07 -0800191/**
192 * Returns the sysfs root path of the input device
193 *
194 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800195static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800196 std::error_code errorCode;
197
198 // Stat the device path to get the major and minor number of the character file
199 struct stat statbuf;
200 if (stat(devicePath, &statbuf) == -1) {
201 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800202 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800203 }
204
205 unsigned int major_num = major(statbuf.st_rdev);
206 unsigned int minor_num = minor(statbuf.st_rdev);
207
208 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
209 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
210 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
211 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
212
213 // Make sure nothing went wrong in call to canonical()
214 if (errorCode) {
215 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
216 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800217 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800218 }
219
220 // Continue to go up a directory until we reach a directory named "input"
221 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
222 sysfsPath = sysfsPath.parent_path();
223 }
224
225 // Then go up one more and you will be at the sysfs root of the device
226 sysfsPath = sysfsPath.parent_path();
227
228 // Make sure we didn't reach root path and that directory actually exists
229 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
230 if (errorCode) {
231 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
232 errorCode.message().c_str());
233 }
234
235 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800236 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800237 }
238
239 return sysfsPath;
240}
241
242/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800243 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800244 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800245static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
246 std::vector<std::filesystem::path> nodes;
247 std::error_code errorCode;
248 auto iter = std::filesystem::directory_iterator(path, errorCode);
249 while (!errorCode && iter != std::filesystem::directory_iterator()) {
250 nodes.push_back(iter->path());
251 iter++;
252 }
253 return nodes;
254}
255
256/**
257 * Returns the list of files under a specified directory in a sysfs path.
258 * Example:
259 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
260 * in the sysfs path.
261 */
262static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
263 SysfsClass clazz) {
264 std::string nodeStr = NamedEnum::string(clazz);
265 std::for_each(nodeStr.begin(), nodeStr.end(),
266 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
267 std::vector<std::filesystem::path> nodes;
268 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
269 nodes = allFilesInPath(path / nodeStr);
270 }
271 return nodes;
272}
273
274static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
275 std::filesystem::path path) {
276 std::string indexStr;
277 if (!base::ReadFileToString(path, &indexStr)) {
278 return std::nullopt;
279 }
280
281 // Parse the multi color LED index file, refer to kernel docs
282 // leds/leds-class-multicolor.html
283 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
284 std::smatch results;
285 std::array<LightColor, COLOR_NUM> colors;
286 if (!std::regex_match(indexStr, results, indexPattern)) {
287 return std::nullopt;
288 }
289
290 for (size_t i = 1; i < results.size(); i++) {
291 const auto it = LIGHT_COLORS.find(results[i].str());
292 if (it != LIGHT_COLORS.end()) {
293 // intensities.emplace(it->second, 0);
294 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800295 }
296 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800297 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800298}
299
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300// --- Global Functions ---
301
Chris Ye1b0c7342020-07-28 21:57:03 -0700302Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800303 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700304 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800305 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700306 case ABS_X:
307 case ABS_Y:
308 case ABS_PRESSURE:
309 case ABS_TOOL_WIDTH:
310 case ABS_DISTANCE:
311 case ABS_TILT_X:
312 case ABS_TILT_Y:
313 case ABS_MT_SLOT:
314 case ABS_MT_TOUCH_MAJOR:
315 case ABS_MT_TOUCH_MINOR:
316 case ABS_MT_WIDTH_MAJOR:
317 case ABS_MT_WIDTH_MINOR:
318 case ABS_MT_ORIENTATION:
319 case ABS_MT_POSITION_X:
320 case ABS_MT_POSITION_Y:
321 case ABS_MT_TOOL_TYPE:
322 case ABS_MT_BLOB_ID:
323 case ABS_MT_TRACKING_ID:
324 case ABS_MT_PRESSURE:
325 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700326 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800327 }
328 }
329
Chris Yef59a2f42020-10-16 12:55:26 -0700330 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
331 switch (axis) {
332 case ABS_X:
333 case ABS_Y:
334 case ABS_Z:
335 case ABS_RX:
336 case ABS_RY:
337 case ABS_RZ:
338 return InputDeviceClass::SENSOR;
339 }
340 }
341
Michael Wright842500e2015-03-13 17:32:02 -0700342 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700343 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700344 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700345 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700346 }
347 }
348
Michael Wrightd02c5b62014-02-10 15:10:22 -0800349 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700350 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800351}
352
353// --- EventHub::Device ---
354
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100355EventHub::Device::Device(int fd, int32_t id, const std::string& path,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700356 const InputDeviceIdentifier& identifier)
Chris Ye989bb932020-07-04 16:18:59 -0700357 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700358 id(id),
359 path(path),
360 identifier(identifier),
361 classes(0),
362 configuration(nullptr),
363 virtualKeyMap(nullptr),
364 ffEffectPlaying(false),
365 ffEffectId(-1),
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700366 associatedDevice(nullptr),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700367 controllerNumber(0),
368 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700369 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370
371EventHub::Device::~Device() {
372 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800373}
374
375void EventHub::Device::close() {
376 if (fd >= 0) {
377 ::close(fd);
378 fd = -1;
379 }
380}
381
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700382status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100383 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700384 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100385 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700386 return -errno;
387 }
388 enabled = true;
389 return OK;
390}
391
392status_t EventHub::Device::disable() {
393 close();
394 enabled = false;
395 return OK;
396}
397
Chris Ye989bb932020-07-04 16:18:59 -0700398bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700399 return !isVirtual && enabled;
400}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800401
Chris Ye3a1e4462020-08-12 10:13:15 -0700402const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700403 return keyMap.keyCharacterMap;
404}
405
406template <std::size_t N>
407status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
408 if (!hasValidFd()) {
409 return BAD_VALUE;
410 }
411 if ((_IOC_SIZE(ioctlCode) == 0)) {
412 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
413 }
414
415 typename BitArray<N>::Buffer buffer;
416 status_t ret = ioctl(fd, ioctlCode, buffer.data());
417 bitArray.loadFromBuffer(buffer);
418 return ret;
419}
420
421void EventHub::Device::configureFd() {
422 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
423 if (classes.test(InputDeviceClass::KEYBOARD)) {
424 // Disable kernel key repeat since we handle it ourselves
425 unsigned int repeatRate[] = {0, 0};
426 if (ioctl(fd, EVIOCSREP, repeatRate)) {
427 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
428 }
429 }
430
431 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
432 // associated with input events. This is important because the input system
433 // uses the timestamps extensively and assumes they were recorded using the monotonic
434 // clock.
435 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700436 if (classes.test(InputDeviceClass::SENSOR)) {
437 // Each new sensor event should use the same time base as
438 // SystemClock.elapsedRealtimeNanos().
439 clockId = CLOCK_BOOTTIME;
440 }
Chris Ye989bb932020-07-04 16:18:59 -0700441 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
442 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
443}
444
445bool EventHub::Device::hasKeycodeLocked(int keycode) const {
446 if (!keyMap.haveKeyLayout()) {
447 return false;
448 }
449
450 std::vector<int32_t> scanCodes;
451 keyMap.keyLayoutMap->findScanCodesForKey(keycode, &scanCodes);
452 const size_t N = scanCodes.size();
453 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
454 int32_t sc = scanCodes[i];
455 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
456 return true;
457 }
458 }
459
460 return false;
461}
462
463void EventHub::Device::loadConfigurationLocked() {
464 configurationFile =
465 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
466 InputDeviceConfigurationFileType::
467 CONFIGURATION);
468 if (configurationFile.empty()) {
469 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
470 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500471 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
472 PropertyMap::load(configurationFile.c_str());
473 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700474 ALOGE("Error loading input device configuration file for device '%s'. "
475 "Using default configuration.",
476 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500477 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500478 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700479 }
480 }
481}
482
483bool EventHub::Device::loadVirtualKeyMapLocked() {
484 // The virtual key map is supplied by the kernel as a system board property file.
485 std::string propPath = "/sys/board_properties/virtualkeys.";
486 propPath += identifier.getCanonicalName();
487 if (access(propPath.c_str(), R_OK)) {
488 return false;
489 }
490 virtualKeyMap = VirtualKeyMap::load(propPath);
491 return virtualKeyMap != nullptr;
492}
493
494status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500495 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700496}
497
498bool EventHub::Device::isExternalDeviceLocked() {
499 if (configuration) {
500 bool value;
501 if (configuration->tryGetProperty(String8("device.internal"), value)) {
502 return !value;
503 }
504 }
505 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
506}
507
508bool EventHub::Device::deviceHasMicLocked() {
509 if (configuration) {
510 bool value;
511 if (configuration->tryGetProperty(String8("audio.mic"), value)) {
512 return value;
513 }
514 }
515 return false;
516}
517
518void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
519 int32_t sc;
520 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
521 struct input_event ev;
522 ev.time.tv_sec = 0;
523 ev.time.tv_usec = 0;
524 ev.type = EV_LED;
525 ev.code = sc;
526 ev.value = on ? 1 : 0;
527
528 ssize_t nWrite;
529 do {
530 nWrite = write(fd, &ev, sizeof(struct input_event));
531 } while (nWrite == -1 && errno == EINTR);
532 }
533}
534
535void EventHub::Device::setLedForControllerLocked() {
536 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
537 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
538 }
539}
540
541status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
542 if (!keyMap.haveKeyLayout()) {
543 return NAME_NOT_FOUND;
544 }
545
546 int32_t scanCode;
547 if (keyMap.keyLayoutMap->findScanCodeForLed(led, &scanCode) != NAME_NOT_FOUND) {
548 if (scanCode >= 0 && scanCode <= LED_MAX && ledBitmask.test(scanCode)) {
549 *outScanCode = scanCode;
550 return NO_ERROR;
551 }
552 }
553 return NAME_NOT_FOUND;
554}
555
Chris Ye3fdbfef2021-01-06 18:45:18 -0800556// Check the sysfs path for any input device batteries, returns true if battery found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700557bool EventHub::AssociatedDevice::configureBatteryLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800558 nextBatteryId = 0;
559 // Check if device has any battery.
560 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
561 for (const auto& nodePath : paths) {
562 RawBatteryInfo info;
563 info.id = ++nextBatteryId;
564 info.path = nodePath;
565 info.name = nodePath.filename();
566
567 // Scan the path for all the files
568 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
569 const auto& files = allFilesInPath(nodePath);
570 for (const auto& file : files) {
571 const auto it = BATTERY_CLASSES.find(file.filename().string());
572 if (it != BATTERY_CLASSES.end()) {
573 info.flags |= it->second;
574 }
575 }
576 batteryInfos.insert_or_assign(info.id, info);
577 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800578 }
Chris Yee2b1e5c2021-03-10 22:45:12 -0800579 return !batteryInfos.empty();
Chris Ye3fdbfef2021-01-06 18:45:18 -0800580}
581
582// Check the sysfs path for any input device lights, returns true if lights found.
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700583bool EventHub::AssociatedDevice::configureLightsLocked() {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800584 nextLightId = 0;
Chris Ye3fdbfef2021-01-06 18:45:18 -0800585 // Check if device has any lights.
Chris Yee2b1e5c2021-03-10 22:45:12 -0800586 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800587 for (const auto& nodePath : paths) {
588 RawLightInfo info;
589 info.id = ++nextLightId;
590 info.path = nodePath;
591 info.name = nodePath.filename();
592 info.maxBrightness = std::nullopt;
593 size_t nameStart = info.name.rfind(":");
594 if (nameStart != std::string::npos) {
595 // Trim the name to color name
596 info.name = info.name.substr(nameStart + 1);
597 // Set InputLightClass flag for colors
598 const auto it = LIGHT_CLASSES.find(info.name);
599 if (it != LIGHT_CLASSES.end()) {
600 info.flags |= it->second;
601 }
602 }
603 // Scan the path for all the files
604 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
605 const auto& files = allFilesInPath(nodePath);
606 for (const auto& file : files) {
607 const auto it = LIGHT_CLASSES.find(file.filename().string());
608 if (it != LIGHT_CLASSES.end()) {
609 info.flags |= it->second;
610 // If the node has maximum brightness, read it
611 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
612 std::string str;
613 if (base::ReadFileToString(file, &str)) {
614 info.maxBrightness = std::stoi(str);
615 }
616 }
617 }
618 }
619 lightInfos.insert_or_assign(info.id, info);
Chris Yee2b1e5c2021-03-10 22:45:12 -0800620 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800621 }
622 return !lightInfos.empty();
623}
624
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100625/**
626 * Get the capabilities for the current process.
627 * Crashes the system if unable to create / check / destroy the capabilities object.
628 */
629class Capabilities final {
630public:
631 explicit Capabilities() {
632 mCaps = cap_get_proc();
633 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
634 }
635
636 /**
637 * Check whether the current process has a specific capability
638 * in the set of effective capabilities.
639 * Return CAP_SET if the process has the requested capability
640 * Return CAP_CLEAR otherwise.
641 */
642 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
643 cap_flag_value_t value;
644 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
645 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
646 return value;
647 }
648
649 ~Capabilities() {
650 const int result = cap_free(mCaps);
651 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
652 }
653
654private:
655 cap_t mCaps;
656};
657
658static void ensureProcessCanBlockSuspend() {
659 Capabilities capabilities;
660 const bool canBlockSuspend =
661 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
662 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
663 "Input must be able to block suspend to properly process events");
664}
665
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666// --- EventHub ---
667
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668const int EventHub::EPOLL_MAX_EVENTS;
669
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700670EventHub::EventHub(void)
671 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
672 mNextDeviceId(1),
673 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800674 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700675 mNeedToReopenDevices(false),
676 mNeedToScanDevices(true),
677 mPendingEventCount(0),
678 mPendingEventIndex(0),
679 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100680 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800681
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800682 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800683 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684
685 mINotifyFd = inotify_init();
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800686 mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700687 LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
688 strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800689 if (isV4lScanningEnabled()) {
690 mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
691 LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700692 VIDEO_DEVICE_PATH, strerror(errno));
Philip Quinn39b81682019-01-09 22:20:39 -0800693 } else {
694 mVideoWd = -1;
695 ALOGI("Video device scanning disabled");
696 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100698 struct epoll_event eventItem = {};
699 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700700 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800701 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800702 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
703
704 int wakeFds[2];
705 result = pipe(wakeFds);
706 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
707
708 mWakeReadPipeFd = wakeFds[0];
709 mWakeWritePipeFd = wakeFds[1];
710
711 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
712 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700713 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800714
715 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
716 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700717 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800718
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700719 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800720 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
721 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700722 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800723}
724
725EventHub::~EventHub(void) {
726 closeAllDevicesLocked();
727
Michael Wrightd02c5b62014-02-10 15:10:22 -0800728 ::close(mEpollFd);
729 ::close(mINotifyFd);
730 ::close(mWakeReadPipeFd);
731 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732}
733
734InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000735 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800736 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700737 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738}
739
Chris Ye1b0c7342020-07-28 21:57:03 -0700740Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000741 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800742 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700743 return device != nullptr ? device->classes : Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800744}
745
746int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000747 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800748 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700749 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800750}
751
752void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000753 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800754 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700755 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800756 *outConfiguration = *device->configuration;
757 } else {
758 outConfiguration->clear();
759 }
760}
761
762status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700763 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800764 outAxisInfo->clear();
765
766 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000767 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800768
769 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700770 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800771 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700772 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
773 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
774 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775 return -errno;
776 }
777
778 if (info.minimum != info.maximum) {
779 outAxisInfo->valid = true;
780 outAxisInfo->minValue = info.minimum;
781 outAxisInfo->maxValue = info.maximum;
782 outAxisInfo->flat = info.flat;
783 outAxisInfo->fuzz = info.fuzz;
784 outAxisInfo->resolution = info.resolution;
785 }
786 return OK;
787 }
788 }
789 return -1;
790}
791
792bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
793 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000794 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800795 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700796 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797 }
798 return false;
799}
800
801bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000802 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800803
Chris Ye989bb932020-07-04 16:18:59 -0700804 Device* device = getDeviceLocked(deviceId);
805 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
806 ? device->propBitmask.test(property)
807 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800808}
809
Chris Yef59a2f42020-10-16 12:55:26 -0700810bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
811 std::scoped_lock _l(mLock);
812
813 Device* device = getDeviceLocked(deviceId);
814 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
815 ? device->mscBitmask.test(mscEvent)
816 : false;
817}
818
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
820 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000821 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822
823 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700824 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
825 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
826 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
828 }
829 }
830 return AKEY_STATE_UNKNOWN;
831}
832
833int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000834 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835
836 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700837 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800838 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode, &scanCodes);
840 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700841 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800843 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700844 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 return AKEY_STATE_DOWN;
846 }
847 }
848 return AKEY_STATE_UP;
849 }
850 }
851 }
852 return AKEY_STATE_UNKNOWN;
853}
854
855int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
856 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000857 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858
859 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700860 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
861 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
862 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 }
864 }
865 }
866 return AKEY_STATE_UNKNOWN;
867}
868
869status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
870 *outValue = 0;
871
872 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000873 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874
875 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700876 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700878 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
879 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
880 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 return -errno;
882 }
883
884 *outValue = info.value;
885 return OK;
886 }
887 }
888 return -1;
889}
890
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700891bool EventHub::markSupportedKeyCodes(int32_t deviceId, size_t numCodes, const int32_t* keyCodes,
892 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000893 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894
895 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700896 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800897 std::vector<int32_t> scanCodes;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 for (size_t codeIndex = 0; codeIndex < numCodes; codeIndex++) {
899 scanCodes.clear();
900
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700901 status_t err = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex],
902 &scanCodes);
903 if (!err) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 // check the possible scan codes identified by the layout map against the
905 // map of codes actually emitted by the driver
906 for (size_t sc = 0; sc < scanCodes.size(); sc++) {
Chris Ye66fbac32020-07-06 20:36:43 -0700907 if (device->keyBitmask.test(scanCodes[sc])) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 outFlags[codeIndex] = 1;
909 break;
910 }
911 }
912 }
913 }
914 return true;
915 }
916 return false;
917}
918
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700919status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
920 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +0000921 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700923 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800924
Chris Ye66fbac32020-07-06 20:36:43 -0700925 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800926 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -0700927 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
928 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800929 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
930 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700931 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800932 }
933 }
934
935 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700936 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800937 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700938 status = NO_ERROR;
939 }
940 }
941
942 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -0700943 if (kcm) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700944 kcm->tryRemapKey(*outKeycode, metaState, outKeycode, outMetaState);
945 } else {
946 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800947 }
948 }
949 }
950
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -0700951 if (status != NO_ERROR) {
952 *outKeycode = 0;
953 *outFlags = 0;
954 *outMetaState = metaState;
955 }
956
957 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +0000961 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962 Device* device = getDeviceLocked(deviceId);
963
Chris Ye66fbac32020-07-06 20:36:43 -0700964 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 status_t err = device->keyMap.keyLayoutMap->mapAxis(scanCode, outAxisInfo);
966 if (err == NO_ERROR) {
967 return NO_ERROR;
968 }
969 }
970
971 return NAME_NOT_FOUND;
972}
973
Chris Yef59a2f42020-10-16 12:55:26 -0700974base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
975 int32_t absCode) {
976 std::scoped_lock _l(mLock);
977 Device* device = getDeviceLocked(deviceId);
978
979 if (device != nullptr && device->keyMap.haveKeyLayout()) {
980 return device->keyMap.keyLayoutMap->mapSensor(absCode);
981 }
982 return Errorf("Device not found or device has no key layout.");
983}
984
Chris Yee2b1e5c2021-03-10 22:45:12 -0800985// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
986// associated with the device ID. Returns an empty map if no miscellaneous device found.
987const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
988 int32_t deviceId) const {
989 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
990 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700991 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -0800992 return EMPTY_BATTERY_INFO;
993 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -0700994 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -0800995}
996
997const std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) {
998 std::scoped_lock _l(mLock);
999 std::vector<int32_t> batteryIds;
1000
1001 for (const auto [id, info] : getBatteryInfoLocked(deviceId)) {
1002 batteryIds.push_back(id);
1003 }
1004
1005 return batteryIds;
1006}
1007
1008std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId, int32_t batteryId) {
1009 std::scoped_lock _l(mLock);
1010
1011 const auto infos = getBatteryInfoLocked(deviceId);
1012
1013 auto it = infos.find(batteryId);
1014 if (it != infos.end()) {
1015 return it->second;
1016 }
1017
1018 return std::nullopt;
1019}
1020
1021// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
1022// with the deivice ID. Returns an empty map if no miscellaneous device found.
1023const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1024 int32_t deviceId) const {
1025 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1026 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001027 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001028 return EMPTY_LIGHT_INFO;
1029 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001030 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001031}
1032
Chris Ye3fdbfef2021-01-06 18:45:18 -08001033const std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) {
1034 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001035 std::vector<int32_t> lightIds;
1036
Chris Yee2b1e5c2021-03-10 22:45:12 -08001037 for (const auto [id, info] : getLightInfoLocked(deviceId)) {
1038 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001039 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001040
Chris Ye3fdbfef2021-01-06 18:45:18 -08001041 return lightIds;
1042}
1043
1044std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) {
1045 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001046
Chris Yee2b1e5c2021-03-10 22:45:12 -08001047 const auto infos = getLightInfoLocked(deviceId);
1048
1049 auto it = infos.find(lightId);
1050 if (it != infos.end()) {
1051 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001052 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001053
Chris Ye3fdbfef2021-01-06 18:45:18 -08001054 return std::nullopt;
1055}
1056
1057std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) {
1058 std::scoped_lock _l(mLock);
1059
Chris Yee2b1e5c2021-03-10 22:45:12 -08001060 const auto infos = getLightInfoLocked(deviceId);
1061 auto it = infos.find(lightId);
1062 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001063 return std::nullopt;
1064 }
1065 std::string buffer;
1066 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1067 &buffer)) {
1068 return std::nullopt;
1069 }
1070 return std::stoi(buffer);
1071}
1072
1073std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
1074 int32_t deviceId, int32_t lightId) {
1075 std::scoped_lock _l(mLock);
1076
Chris Yee2b1e5c2021-03-10 22:45:12 -08001077 const auto infos = getLightInfoLocked(deviceId);
1078 auto lightIt = infos.find(lightId);
1079 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001080 return std::nullopt;
1081 }
1082
1083 auto ret =
1084 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1085
1086 if (!ret.has_value()) {
1087 return std::nullopt;
1088 }
1089 std::array<LightColor, COLOR_NUM> colors = ret.value();
1090
1091 std::string intensityStr;
1092 if (!base::ReadFileToString(lightIt->second.path /
1093 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1094 &intensityStr)) {
1095 return std::nullopt;
1096 }
1097
1098 // Intensity node outputs 3 color values
1099 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1100 std::smatch results;
1101
1102 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1103 return std::nullopt;
1104 }
1105 std::unordered_map<LightColor, int32_t> intensities;
1106 for (size_t i = 1; i < results.size(); i++) {
1107 int value = std::stoi(results[i].str());
1108 intensities.emplace(colors[i - 1], value);
1109 }
1110 return intensities;
1111}
1112
1113void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1114 std::scoped_lock _l(mLock);
1115
Chris Yee2b1e5c2021-03-10 22:45:12 -08001116 const auto infos = getLightInfoLocked(deviceId);
1117 auto lightIt = infos.find(lightId);
1118 if (lightIt == infos.end()) {
1119 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001120 return;
1121 }
1122
1123 if (!base::WriteStringToFile(std::to_string(brightness),
1124 lightIt->second.path /
1125 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1126 ALOGE("Can not write to file, error: %s", strerror(errno));
1127 }
1128}
1129
1130void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1131 std::unordered_map<LightColor, int32_t> intensities) {
1132 std::scoped_lock _l(mLock);
1133
Chris Yee2b1e5c2021-03-10 22:45:12 -08001134 const auto infos = getLightInfoLocked(deviceId);
1135 auto lightIt = infos.find(lightId);
1136 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001137 ALOGE("Light Id %d does not exist.", lightId);
1138 return;
1139 }
1140
1141 auto ret =
1142 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1143
1144 if (!ret.has_value()) {
1145 return;
1146 }
1147 std::array<LightColor, COLOR_NUM> colors = ret.value();
1148
1149 std::string rgbStr;
1150 for (size_t i = 0; i < COLOR_NUM; i++) {
1151 auto it = intensities.find(colors[i]);
1152 if (it != intensities.end()) {
1153 rgbStr += std::to_string(it->second);
1154 // Insert space between colors
1155 if (i < COLOR_NUM - 1) {
1156 rgbStr += " ";
1157 }
1158 }
1159 }
1160 // Append new line
1161 rgbStr += "\n";
1162
1163 if (!base::WriteStringToFile(rgbStr,
1164 lightIt->second.path /
1165 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1166 ALOGE("Can not write to file, error: %s", strerror(errno));
1167 }
1168}
1169
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001170void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001171 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172
1173 mExcludedDevices = devices;
1174}
1175
1176bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001177 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001178 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001179 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1180 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181 }
1182 return false;
1183}
1184
1185bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001186 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 Device* device = getDeviceLocked(deviceId);
1188 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001189 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001190 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 }
1192 return false;
1193}
1194
1195void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001196 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001197 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001198 if (device != nullptr && device->hasValidFd()) {
1199 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001200 }
1201}
1202
1203void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001204 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 outVirtualKeys.clear();
1206
Chris Ye87143712020-11-10 05:05:58 +00001207 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001208 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001209 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001210 const std::vector<VirtualKeyDefinition> virtualKeys =
1211 device->virtualKeyMap->getVirtualKeys();
1212 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213 }
1214}
1215
Chris Ye3a1e4462020-08-12 10:13:15 -07001216const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001217 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001219 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001220 return device->getKeyCharacterMap();
1221 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001222 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223}
1224
Chris Ye3a1e4462020-08-12 10:13:15 -07001225bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001226 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001227 Device* device = getDeviceLocked(deviceId);
Chris Ye3a1e4462020-08-12 10:13:15 -07001228 if (device != nullptr && map != nullptr && device->keyMap.keyCharacterMap != nullptr) {
1229 device->keyMap.keyCharacterMap->combine(*map);
1230 device->keyMap.keyCharacterMapFile = device->keyMap.keyCharacterMap->getLoadFileName();
1231 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 }
1233 return false;
1234}
1235
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001236static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1237 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001238 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001240 if (!identifier.uniqueId.empty()) {
1241 rawDescriptor += "uniqueId:";
1242 rawDescriptor += identifier.uniqueId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001243 } else if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001244 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001245 }
1246
1247 if (identifier.vendor == 0 && identifier.product == 0) {
1248 // If we don't know the vendor and product id, then the device is probably
1249 // built-in so we need to rely on other information to uniquely identify
1250 // the input device. Usually we try to avoid relying on the device name or
1251 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001252 if (!identifier.name.empty()) {
1253 rawDescriptor += "name:";
1254 rawDescriptor += identifier.name;
1255 } else if (!identifier.location.empty()) {
1256 rawDescriptor += "location:";
1257 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258 }
1259 }
1260 identifier.descriptor = sha1(rawDescriptor);
1261 return rawDescriptor;
1262}
1263
1264void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1265 // Compute a device descriptor that uniquely identifies the device.
1266 // The descriptor is assumed to be a stable identifier. Its value should not
1267 // change between reboots, reconnections, firmware updates or new releases
1268 // of Android. In practice we sometimes get devices that cannot be uniquely
1269 // identified. In this case we enforce uniqueness between connected devices.
1270 // Ideally, we also want the descriptor to be short and relatively opaque.
1271
1272 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001273 std::string rawDescriptor = generateDescriptor(identifier);
1274 if (identifier.uniqueId.empty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 // If it didn't have a unique id check for conflicts and enforce
1276 // uniqueness if necessary.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001277 while (getDeviceByDescriptorLocked(identifier.descriptor) != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 identifier.nonce++;
1279 rawDescriptor = generateDescriptor(identifier);
1280 }
1281 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001282 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001283 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001284}
1285
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001286void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001287 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001289 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001290 ff_effect effect;
1291 memset(&effect, 0, sizeof(effect));
1292 effect.type = FF_RUMBLE;
1293 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001294 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001295 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1296 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001297 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001298 effect.replay.delay = 0;
1299 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1300 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001301 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302 return;
1303 }
1304 device->ffEffectId = effect.id;
1305
1306 struct input_event ev;
1307 ev.time.tv_sec = 0;
1308 ev.time.tv_usec = 0;
1309 ev.type = EV_FF;
1310 ev.code = device->ffEffectId;
1311 ev.value = 1;
1312 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1313 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001314 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001315 return;
1316 }
1317 device->ffEffectPlaying = true;
1318 }
1319}
1320
1321void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001322 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001323 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001324 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325 if (device->ffEffectPlaying) {
1326 device->ffEffectPlaying = false;
1327
1328 struct input_event ev;
1329 ev.time.tv_sec = 0;
1330 ev.time.tv_usec = 0;
1331 ev.type = EV_FF;
1332 ev.code = device->ffEffectId;
1333 ev.value = 0;
1334 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1335 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001336 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 return;
1338 }
1339 }
1340 }
1341}
1342
Chris Ye87143712020-11-10 05:05:58 +00001343std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) {
1344 std::scoped_lock _l(mLock);
1345 std::vector<int32_t> vibrators;
1346 Device* device = getDeviceLocked(deviceId);
1347 if (device != nullptr && device->hasValidFd() &&
1348 device->classes.test(InputDeviceClass::VIBRATOR)) {
1349 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1350 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1351 }
1352 return vibrators;
1353}
1354
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001355EventHub::Device* EventHub::getDeviceByDescriptorLocked(const std::string& descriptor) const {
Chris Ye989bb932020-07-04 16:18:59 -07001356 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001357 if (descriptor == device->identifier.descriptor) {
Chris Ye989bb932020-07-04 16:18:59 -07001358 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001359 }
1360 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001361 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001362}
1363
1364EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001365 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366 deviceId = mBuiltInKeyboardId;
1367 }
Chris Ye989bb932020-07-04 16:18:59 -07001368 const auto& it = mDevices.find(deviceId);
1369 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370}
1371
Chris Ye8594e192020-07-14 10:34:06 -07001372EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001373 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001374 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001375 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001376 }
1377 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001378 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001379}
1380
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001381/**
1382 * The file descriptor could be either input device, or a video device (associated with a
1383 * specific input device). Check both cases here, and return the device that this event
1384 * belongs to. Caller can compare the fd's once more to determine event type.
1385 * Looks through all input devices, and only attached video devices. Unattached video
1386 * devices are ignored.
1387 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001388EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001389 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001390 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001391 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001392 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001393 }
1394 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1395 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001396 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001397 }
1398 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001399 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1400 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001401 return nullptr;
1402}
1403
Chris Yee2b1e5c2021-03-10 22:45:12 -08001404std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001405 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001406
Chris Yee2b1e5c2021-03-10 22:45:12 -08001407 const auto infos = getBatteryInfoLocked(deviceId);
1408 auto it = infos.find(batteryId);
1409 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001410 return std::nullopt;
1411 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001412 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001413
1414 // Some devices report battery capacity as an integer through the "capacity" file
Chris Yee2b1e5c2021-03-10 22:45:12 -08001415 if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
1416 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001417 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001418 }
1419
1420 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1421 // These values are taken from kernel source code include/linux/power_supply.h
Chris Yee2b1e5c2021-03-10 22:45:12 -08001422 if (base::ReadFileToString(it->second.path /
1423 BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
1424 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001425 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001426 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1427 if (levelIt != BATTERY_LEVEL.end()) {
1428 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001429 }
1430 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001431
Kim Low03ea0352020-11-06 12:45:07 -08001432 return std::nullopt;
1433}
1434
Chris Yee2b1e5c2021-03-10 22:45:12 -08001435std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Kim Low03ea0352020-11-06 12:45:07 -08001436 std::scoped_lock _l(mLock);
Chris Yee2b1e5c2021-03-10 22:45:12 -08001437 const auto infos = getBatteryInfoLocked(deviceId);
1438 auto it = infos.find(batteryId);
1439 if (it == infos.end()) {
Kim Low03ea0352020-11-06 12:45:07 -08001440 return std::nullopt;
1441 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001442 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001443
Chris Yee2b1e5c2021-03-10 22:45:12 -08001444 if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
1445 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001446 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1447 return std::nullopt;
1448 }
1449
Chris Yed1936772021-02-22 10:30:40 -08001450 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001451 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1452 if (statusIt != BATTERY_STATUS.end()) {
1453 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001454 }
1455
1456 return std::nullopt;
1457}
1458
Michael Wrightd02c5b62014-02-10 15:10:22 -08001459size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
1460 ALOG_ASSERT(bufferSize >= 1);
1461
Chris Ye87143712020-11-10 05:05:58 +00001462 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463
1464 struct input_event readBuffer[bufferSize];
1465
1466 RawEvent* event = buffer;
1467 size_t capacity = bufferSize;
1468 bool awoken = false;
1469 for (;;) {
1470 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1471
1472 // Reopen input devices if needed.
1473 if (mNeedToReopenDevices) {
1474 mNeedToReopenDevices = false;
1475
1476 ALOGI("Reopening all input devices due to a configuration change.");
1477
1478 closeAllDevicesLocked();
1479 mNeedToScanDevices = true;
1480 break; // return to the caller before we actually rescan
1481 }
1482
1483 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001484 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1485 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001486 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001487 event->when = now;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001488 event->deviceId = (device->id == mBuiltInKeyboardId)
1489 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1490 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 event->type = DEVICE_REMOVED;
1492 event += 1;
Chris Ye989bb932020-07-04 16:18:59 -07001493 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 mNeedToSendFinishedDeviceScan = true;
1495 if (--capacity == 0) {
1496 break;
1497 }
1498 }
1499
1500 if (mNeedToScanDevices) {
1501 mNeedToScanDevices = false;
1502 scanDevicesLocked();
1503 mNeedToSendFinishedDeviceScan = true;
1504 }
1505
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001506 while (!mOpeningDevices.empty()) {
1507 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1508 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001509 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 event->when = now;
1511 event->deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1512 event->type = DEVICE_ADDED;
1513 event += 1;
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001514
1515 // Try to find a matching video device by comparing device names
1516 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1517 it++) {
1518 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001519 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001520 // videoDevice was transferred to 'device'
1521 it = mUnattachedVideoDevices.erase(it);
1522 break;
1523 }
1524 }
1525
1526 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1527 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001528 ALOGW("Device id %d exists, replaced.", device->id);
1529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 mNeedToSendFinishedDeviceScan = true;
1531 if (--capacity == 0) {
1532 break;
1533 }
1534 }
1535
1536 if (mNeedToSendFinishedDeviceScan) {
1537 mNeedToSendFinishedDeviceScan = false;
1538 event->when = now;
1539 event->type = FINISHED_DEVICE_SCAN;
1540 event += 1;
1541 if (--capacity == 0) {
1542 break;
1543 }
1544 }
1545
1546 // Grab the next input event.
1547 bool deviceChanged = false;
1548 while (mPendingEventIndex < mPendingEventCount) {
1549 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001550 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 if (eventItem.events & EPOLLIN) {
1552 mPendingINotify = true;
1553 } else {
1554 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1555 }
1556 continue;
1557 }
1558
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001559 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001560 if (eventItem.events & EPOLLIN) {
1561 ALOGV("awoken after wake()");
1562 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001563 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001564 ssize_t nRead;
1565 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001566 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1567 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 } else {
1569 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001570 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 }
1572 continue;
1573 }
1574
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001575 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001576 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001577 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1578 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001579 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001580 continue;
1581 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001582 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1583 if (eventItem.events & EPOLLIN) {
1584 size_t numFrames = device->videoDevice->readAndQueueFrames();
1585 if (numFrames == 0) {
1586 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001587 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001588 }
1589 } else if (eventItem.events & EPOLLHUP) {
1590 // TODO(b/121395353) - consider adding EPOLLRDHUP
1591 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001592 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001593 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1594 device->videoDevice = nullptr;
1595 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001596 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1597 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001598 ALOG_ASSERT(!DEBUG);
1599 }
1600 continue;
1601 }
1602 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001603 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001604 int32_t readSize =
1605 read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001606 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1607 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001608 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001609 " bufferSize: %zu capacity: %zu errno: %d)\n",
1610 device->fd, readSize, bufferSize, capacity, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001611 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001612 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001613 } else if (readSize < 0) {
1614 if (errno != EAGAIN && errno != EINTR) {
1615 ALOGW("could not get event (errno=%d)", errno);
1616 }
1617 } else if ((readSize % sizeof(struct input_event)) != 0) {
1618 ALOGE("could not get event (wrong size: %d)", readSize);
1619 } else {
1620 int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1621
1622 size_t count = size_t(readSize) / sizeof(struct input_event);
1623 for (size_t i = 0; i < count; i++) {
1624 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001625 event->when = processEventTimestamp(iev);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001626 event->readTime = systemTime(SYSTEM_TIME_MONOTONIC);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627 event->deviceId = deviceId;
1628 event->type = iev.type;
1629 event->code = iev.code;
1630 event->value = iev.value;
1631 event += 1;
1632 capacity -= 1;
1633 }
1634 if (capacity == 0) {
1635 // The result buffer is full. Reset the pending event index
1636 // so we will try to read the device again on the next iteration.
1637 mPendingEventIndex -= 1;
1638 break;
1639 }
1640 }
1641 } else if (eventItem.events & EPOLLHUP) {
1642 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001643 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001645 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001646 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001647 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1648 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 }
1650 }
1651
1652 // readNotify() will modify the list of devices so this must be done after
1653 // processing all other events to ensure that we read all remaining events
1654 // before closing the devices.
1655 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1656 mPendingINotify = false;
1657 readNotifyLocked();
1658 deviceChanged = true;
1659 }
1660
1661 // Report added or removed devices immediately.
1662 if (deviceChanged) {
1663 continue;
1664 }
1665
1666 // Return now if we have collected any events or if we were explicitly awoken.
1667 if (event != buffer || awoken) {
1668 break;
1669 }
1670
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001671 // Poll for events.
1672 // When a device driver has pending (unread) events, it acquires
1673 // a kernel wake lock. Once the last pending event has been read, the device
1674 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1675 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1676 // is called again for the same fd that produced the event.
1677 // Thus the system can only sleep if there are no events pending or
1678 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679 //
1680 // The timeout is advisory only. If the device is asleep, it will not wake just to
1681 // service the timeout.
1682 mPendingEventIndex = 0;
1683
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001684 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685
1686 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1687
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001688 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001689
1690 if (pollResult == 0) {
1691 // Timed out.
1692 mPendingEventCount = 0;
1693 break;
1694 }
1695
1696 if (pollResult < 0) {
1697 // An error occurred.
1698 mPendingEventCount = 0;
1699
1700 // Sleep after errors to avoid locking up the system.
1701 // Hopefully the error is transient.
1702 if (errno != EINTR) {
1703 ALOGW("poll failed (errno=%d)\n", errno);
1704 usleep(100000);
1705 }
1706 } else {
1707 // Some events occurred.
1708 mPendingEventCount = size_t(pollResult);
1709 }
1710 }
1711
1712 // All done, return the number of events we read.
1713 return event - buffer;
1714}
1715
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001716std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001717 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001718
1719 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001720 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001721 return {};
1722 }
1723 return device->videoDevice->consumeFrames();
1724}
1725
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726void EventHub::wake() {
1727 ALOGV("wake() called");
1728
1729 ssize_t nWrite;
1730 do {
1731 nWrite = write(mWakeWritePipeFd, "W", 1);
1732 } while (nWrite == -1 && errno == EINTR);
1733
1734 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001735 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737}
1738
1739void EventHub::scanDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001740 status_t result = scanDirLocked(DEVICE_PATH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001741 if (result < 0) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001742 ALOGE("scan dir failed for %s", DEVICE_PATH);
1743 }
Philip Quinn39b81682019-01-09 22:20:39 -08001744 if (isV4lScanningEnabled()) {
1745 result = scanVideoDirLocked(VIDEO_DEVICE_PATH);
1746 if (result != OK) {
1747 ALOGE("scan video dir failed for %s", VIDEO_DEVICE_PATH);
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 }
Chris Ye989bb932020-07-04 16:18:59 -07001750 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 createVirtualKeyboardLocked();
1752 }
1753}
1754
1755// ----------------------------------------------------------------------------
1756
Michael Wrightd02c5b62014-02-10 15:10:22 -08001757static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001758 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1759 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1760 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1761 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1762 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1763 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764};
1765
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001766status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001767 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001768 struct epoll_event eventItem = {};
1769 eventItem.events = EPOLLIN | EPOLLWAKEUP;
1770 eventItem.data.fd = fd;
1771 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
1772 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001773 return -errno;
1774 }
1775 return OK;
1776}
1777
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001778status_t EventHub::unregisterFdFromEpoll(int fd) {
1779 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
1780 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
1781 return -errno;
1782 }
1783 return OK;
1784}
1785
Chris Ye989bb932020-07-04 16:18:59 -07001786status_t EventHub::registerDeviceForEpollLocked(Device& device) {
1787 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001788 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001789 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001790 return result;
1791 }
Chris Ye989bb932020-07-04 16:18:59 -07001792 if (device.videoDevice) {
1793 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001794 }
1795 return result;
1796}
1797
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001798void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
1799 status_t result = registerFdForEpoll(videoDevice.getFd());
1800 if (result != OK) {
1801 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
1802 }
1803}
1804
Chris Ye989bb932020-07-04 16:18:59 -07001805status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
1806 if (device.hasValidFd()) {
1807 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001808 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07001809 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08001810 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001811 }
1812 }
Chris Ye989bb932020-07-04 16:18:59 -07001813 if (device.videoDevice) {
1814 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001815 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001816 return OK;
1817}
1818
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001819void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
1820 if (videoDevice.hasValidFd()) {
1821 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
1822 if (result != OK) {
1823 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001824 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001825 }
1826 }
1827}
1828
Chris Yed3fef462021-03-07 17:10:08 -08001829void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
1830 Flags<InputDeviceClass> classes) {
1831 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
1832 identifier.vendor, identifier.product, identifier.version,
1833 identifier.bus, identifier.uniqueId.c_str(), classes.get());
1834}
1835
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001836void EventHub::openDeviceLocked(const std::string& devicePath) {
1837 // If an input device happens to register around the time when EventHub's constructor runs, it
1838 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
1839 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
1840 // from getting registered, ensure that this path is not already covered by an existing device.
1841 for (const auto& [deviceId, device] : mDevices) {
1842 if (device->path == devicePath) {
1843 return; // device was already registered
1844 }
1845 }
1846
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 char buffer[80];
1848
Chris Ye8594e192020-07-14 10:34:06 -07001849 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001850
Chris Ye8594e192020-07-14 10:34:06 -07001851 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001852 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07001853 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001854 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001855 }
1856
1857 InputDeviceIdentifier identifier;
1858
1859 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001860 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07001861 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001862 } else {
1863 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001864 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 }
1866
1867 // Check to see if the device is on our excluded list
1868 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001869 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07001871 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001873 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001874 }
1875 }
1876
1877 // Get device driver version.
1878 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001879 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07001880 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001881 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001882 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001883 }
1884
1885 // Get device identifier.
1886 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001887 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07001888 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001889 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00001890 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001891 }
1892 identifier.bus = inputId.bustype;
1893 identifier.product = inputId.product;
1894 identifier.vendor = inputId.vendor;
1895 identifier.version = inputId.version;
1896
1897 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001898 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
1899 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 } else {
1901 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001902 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 }
1904
1905 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001906 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
1907 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001908 } else {
1909 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001910 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001911 }
1912
1913 // Fill in the descriptor.
1914 assignDescriptorLocked(identifier);
1915
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 // Allocate device. (The device object takes ownership of the fd at this point.)
1917 int32_t deviceId = mNextDeviceId++;
Chris Ye989bb932020-07-04 16:18:59 -07001918 std::unique_ptr<Device> device = std::make_unique<Device>(fd, deviceId, devicePath, identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001919
Chris Ye8594e192020-07-14 10:34:06 -07001920 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001921 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001922 " vendor %04x\n"
1923 " product %04x\n"
1924 " version %04x\n",
1925 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001926 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
1927 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
1928 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
1929 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001930 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
1931 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001932
1933 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07001934 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935
Chris Yee2b1e5c2021-03-10 22:45:12 -08001936 bool hasBattery = false;
1937 bool hasLights = false;
1938 // Check the sysfs root path
1939 std::optional<std::filesystem::path> sysfsRootPath = getSysfsRootPath(devicePath.c_str());
1940 if (sysfsRootPath.has_value()) {
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001941 std::shared_ptr<AssociatedDevice> associatedDevice;
1942 for (const auto& [id, dev] : mDevices) {
1943 if (device->identifier.descriptor == dev->identifier.descriptor &&
1944 !dev->associatedDevice) {
1945 associatedDevice = dev->associatedDevice;
1946 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001947 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001948 if (!associatedDevice) {
1949 associatedDevice = std::make_shared<AssociatedDevice>(sysfsRootPath.value());
1950 }
1951 hasBattery = associatedDevice->configureBatteryLocked();
1952 hasLights = associatedDevice->configureLightsLocked();
Chris Yee2b1e5c2021-03-10 22:45:12 -08001953
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001954 device->associatedDevice = associatedDevice;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001955 }
Chris Ye3fdbfef2021-01-06 18:45:18 -08001956
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07001958 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
1959 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
1960 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
1961 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
1962 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
1963 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07001964 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07001965 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001966
1967 // See if this is a keyboard. Ignore everything in the button range except for
1968 // joystick and gamepad buttons which are handled like keyboards for the most part.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001969 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07001970 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
1971 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
1972 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973 if (haveKeyboardKeys || haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001974 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 }
1976
1977 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07001978 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
1979 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001980 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981 }
1982
Prashant Malani1941ff52015-08-11 18:29:28 -07001983 // See if this is a rotary encoder type device.
1984 String8 deviceType = String8();
1985 if (device->configuration &&
1986 device->configuration->tryGetProperty(String8("device.type"), deviceType)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001987 if (!deviceType.compare(String8("rotaryEncoder"))) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001988 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001989 }
Prashant Malani1941ff52015-08-11 18:29:28 -07001990 }
1991
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992 // See if this is a touch pad.
1993 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07001994 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001995 // Some joysticks such as the PS3 controller report axes that conflict
1996 // with the ABS_MT range. Try to confirm that the device really is
1997 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07001998 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07001999 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002001 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002002 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2003 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002004 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002005 // Is this a BT stylus?
Chris Ye66fbac32020-07-06 20:36:43 -07002006 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2007 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002008 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -07002009 // Keyboard will try to claim some of the buttons but we really want to reserve those so we
2010 // can fuse it with the touch screen data, so just take them back. Note this means an
2011 // external stylus cannot also be a keyboard device.
Chris Ye1b0c7342020-07-28 21:57:03 -07002012 device->classes &= ~InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014
2015 // See if this device is a joystick.
2016 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2017 // from other devices such as accelerometers that also have absolute axes.
2018 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002019 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002021 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002022 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002023 device->classes = assumedClasses;
2024 break;
2025 }
2026 }
2027 }
2028
Chris Yef59a2f42020-10-16 12:55:26 -07002029 // Check whether this device is an accelerometer.
2030 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2031 device->classes |= InputDeviceClass::SENSOR;
2032 }
2033
Michael Wrightd02c5b62014-02-10 15:10:22 -08002034 // Check whether this device has switches.
2035 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002036 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002037 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038 break;
2039 }
2040 }
2041
2042 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002043 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002044 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 }
2046
2047 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002048 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 // Load the virtual keys for the touch screen, if any.
2050 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002051 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002052 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002053 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002054 }
2055 }
2056
2057 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002058 // We need to do this for joysticks too because the key layout may specify axes, and for
2059 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002061 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2062 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002064 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 }
2066
2067 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002068 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002070 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002071 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2072 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073 mBuiltInKeyboardId = device->id;
2074 }
2075
2076 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002077 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002078 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002079 }
2080
2081 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002082 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2083 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2084 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2085 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2086 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002087 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 }
2089
2090 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002091 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002092 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002093 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 break;
2095 }
2096 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 }
2098
2099 // If the device isn't recognized as something we handle, don't monitor it.
Chris Ye1b0c7342020-07-28 21:57:03 -07002100 if (device->classes == Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002101 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002102 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002103 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
2105
Chris Ye3fdbfef2021-01-06 18:45:18 -08002106 // Classify InputDeviceClass::BATTERY.
2107 if (hasBattery) {
2108 device->classes |= InputDeviceClass::BATTERY;
2109 }
Kim Low03ea0352020-11-06 12:45:07 -08002110
Chris Ye3fdbfef2021-01-06 18:45:18 -08002111 // Classify InputDeviceClass::LIGHT.
2112 if (hasLights) {
2113 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002114 }
2115
Tim Kilbourn063ff532015-04-08 10:26:18 -07002116 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002117 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002118 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002119 }
2120
Michael Wrightd02c5b62014-02-10 15:10:22 -08002121 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002122 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002123 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002124 }
2125
Chris Ye1b0c7342020-07-28 21:57:03 -07002126 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2127 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002128 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2129 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 }
2131
Chris Ye989bb932020-07-04 16:18:59 -07002132 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002133 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002134 }
2135
Chris Ye989bb932020-07-04 16:18:59 -07002136 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002137
Chris Ye1b0c7342020-07-28 21:57:03 -07002138 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002139 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002140 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2141 device->classes.string().c_str(), device->configurationFile.c_str(),
2142 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2143 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002144
Chris Ye989bb932020-07-04 16:18:59 -07002145 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002146}
2147
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002148void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2149 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2150 if (!videoDevice) {
2151 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2152 return;
2153 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002154 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002155 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002156 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002157 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002158 }
2159 }
2160
2161 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2162 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002163 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002164 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002165 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2166}
2167
Chris Yed3fef462021-03-07 17:10:08 -08002168bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2169 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002170 if (videoDevice->getName() != device.identifier.name) {
2171 return false;
2172 }
2173 device.videoDevice = std::move(videoDevice);
2174 if (device.enabled) {
2175 registerVideoDeviceForEpollLocked(*device.videoDevice);
2176 }
2177 return true;
2178}
2179
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002180bool EventHub::isDeviceEnabled(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002181 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002182 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002183 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002184 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2185 return false;
2186 }
2187 return device->enabled;
2188}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002189
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002190status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002191 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002192 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002193 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002194 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2195 return BAD_VALUE;
2196 }
2197 if (device->enabled) {
2198 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2199 return OK;
2200 }
2201 status_t result = device->enable();
2202 if (result != OK) {
2203 ALOGE("Failed to enable device %" PRId32, deviceId);
2204 return result;
2205 }
2206
Chris Ye989bb932020-07-04 16:18:59 -07002207 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002208
Chris Ye989bb932020-07-04 16:18:59 -07002209 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002210}
2211
2212status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002213 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002214 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002215 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002216 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2217 return BAD_VALUE;
2218 }
2219 if (!device->enabled) {
2220 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2221 return OK;
2222 }
Chris Ye989bb932020-07-04 16:18:59 -07002223 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002224 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002225}
2226
2227void EventHub::createVirtualKeyboardLocked() {
2228 InputDeviceIdentifier identifier;
2229 identifier.name = "Virtual";
2230 identifier.uniqueId = "<virtual>";
2231 assignDescriptorLocked(identifier);
2232
Chris Ye989bb932020-07-04 16:18:59 -07002233 std::unique_ptr<Device> device =
2234 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
2235 identifier);
Chris Ye1b0c7342020-07-28 21:57:03 -07002236 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2237 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002238 device->loadKeyMapLocked();
2239 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002240}
2241
Chris Ye989bb932020-07-04 16:18:59 -07002242void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002243 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002244 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245}
2246
Chris Ye989bb932020-07-04 16:18:59 -07002247int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 if (mControllerNumbers.isFull()) {
2249 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002250 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 return 0;
2252 }
2253 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2254 // one
2255 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2256}
2257
Chris Ye989bb932020-07-04 16:18:59 -07002258void EventHub::releaseControllerNumberLocked(int32_t num) {
2259 if (num > 0) {
2260 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262}
2263
Chris Ye8594e192020-07-14 10:34:06 -07002264void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002266 if (device != nullptr) {
2267 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002268 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
Chris Ye8594e192020-07-14 10:34:06 -07002270 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002271}
2272
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002273/**
2274 * Find the video device by filename, and close it.
2275 * The video device is closed by path during an inotify event, where we don't have the
2276 * additional context about the video device fd, or the associated input device.
2277 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002278void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002279 // A video device may be owned by an existing input device, or it may be stored in
2280 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002281 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002282 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002283 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002284 device->videoDevice = nullptr;
2285 return;
2286 }
2287 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002288 mUnattachedVideoDevices
2289 .erase(std::remove_if(mUnattachedVideoDevices.begin(), mUnattachedVideoDevices.end(),
2290 [&devicePath](
2291 const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2292 return videoDevice->getPath() == devicePath;
2293 }),
2294 mUnattachedVideoDevices.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295}
2296
2297void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002298 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002299 while (!mDevices.empty()) {
2300 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 }
2302}
2303
Chris Ye989bb932020-07-04 16:18:59 -07002304void EventHub::closeDeviceLocked(Device& device) {
2305 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2306 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307
Chris Ye989bb932020-07-04 16:18:59 -07002308 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002309 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002310 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002311 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2312 }
2313
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002314 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002315 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002316 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002317 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319
Chris Ye989bb932020-07-04 16:18:59 -07002320 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002321 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002322 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002323 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002324
Chris Ye989bb932020-07-04 16:18:59 -07002325 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326}
2327
2328status_t EventHub::readNotifyLocked() {
2329 int res;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002330 char event_buf[512];
2331 int event_size;
2332 int event_pos = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002333 struct inotify_event* event;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334
2335 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
2336 res = read(mINotifyFd, event_buf, sizeof(event_buf));
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002337 if (res < (int)sizeof(*event)) {
2338 if (errno == EINTR) return 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 ALOGW("could not get event, %s\n", strerror(errno));
2340 return -1;
2341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002342
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002343 while (res >= (int)sizeof(*event)) {
2344 event = (struct inotify_event*)(event_buf + event_pos);
2345 if (event->len) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002346 if (event->wd == mInputWd) {
Chris Ye8594e192020-07-14 10:34:06 -07002347 std::string filename = std::string(DEVICE_PATH) + "/" + event->name;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002348 if (event->mask & IN_CREATE) {
Chris Ye8594e192020-07-14 10:34:06 -07002349 openDeviceLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002350 } else {
2351 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
Chris Ye8594e192020-07-14 10:34:06 -07002352 closeDeviceByPathLocked(filename);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002353 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002354 } else if (event->wd == mVideoWd) {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002355 if (isV4lTouchNode(event->name)) {
Chris Ye8594e192020-07-14 10:34:06 -07002356 std::string filename = std::string(VIDEO_DEVICE_PATH) + "/" + event->name;
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002357 if (event->mask & IN_CREATE) {
2358 openVideoDeviceLocked(filename);
2359 } else {
2360 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2361 closeVideoDeviceByPathLocked(filename);
2362 }
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002363 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002364 } else {
Siarhei Vishniakou951f3622018-12-12 19:45:42 -08002365 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
2367 }
2368 event_size = sizeof(*event) + event->len;
2369 res -= event_size;
2370 event_pos += event_size;
2371 }
2372 return 0;
2373}
2374
Chris Ye8594e192020-07-14 10:34:06 -07002375status_t EventHub::scanDirLocked(const std::string& dirname) {
2376 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2377 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379 return 0;
2380}
2381
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002382/**
2383 * Look for all dirname/v4l-touch* devices, and open them.
2384 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002385status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002386 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2387 if (isV4lTouchNode(entry.path())) {
2388 ALOGI("Found touch video device %s", entry.path().c_str());
2389 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002390 }
2391 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002392 return OK;
2393}
2394
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395void EventHub::requestReopenDevices() {
2396 ALOGV("requestReopenDevices() called");
2397
Chris Ye87143712020-11-10 05:05:58 +00002398 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 mNeedToReopenDevices = true;
2400}
2401
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002402void EventHub::dump(std::string& dump) {
2403 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404
2405 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002406 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002408 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002410 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411
Chris Ye989bb932020-07-04 16:18:59 -07002412 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002414 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002415 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002417 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002418 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002420 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002421 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002422 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002423 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2424 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002425 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002426 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002427 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002428 "product=0x%04x, version=0x%04x\n",
2429 device->identifier.bus, device->identifier.vendor,
2430 device->identifier.product, device->identifier.version);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002431 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002432 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002433 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002434 device->keyMap.keyCharacterMapFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002435 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002436 device->configurationFile.c_str());
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002437 dump += INDENT3 "VideoDevice: ";
2438 if (device->videoDevice) {
2439 dump += device->videoDevice->dump() + "\n";
2440 } else {
2441 dump += "<none>\n";
2442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002444
2445 dump += INDENT "Unattached video devices:\n";
2446 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2447 dump += INDENT2 + videoDevice->dump() + "\n";
2448 }
2449 if (mUnattachedVideoDevices.empty()) {
2450 dump += INDENT2 "<none>\n";
2451 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002452 } // release lock
2453}
2454
2455void EventHub::monitor() {
2456 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002457 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458}
2459
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460}; // namespace android