blob: e9fa599b3315c030634e5da6e643d20565f2c1fe [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>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.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>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000046#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070048#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080049#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <utils/Log.h>
52#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Chris Ye8594e192020-07-14 10:34:06 -070054#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080055#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000056#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070057
58#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Michael Wrightd02c5b62014-02-10 15:10:22 -080060#define INDENT " "
61#define INDENT2 " "
62#define INDENT3 " "
63
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064using android::base::StringPrintf;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +000065using android::hardware::input::InputDeviceCountryCode;
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080066
Michael Wrightd02c5b62014-02-10 15:10:22 -080067namespace android {
68
Dominik Laskowski2f01d772022-03-23 16:01:29 -070069using namespace ftl::flag_operators;
70
Usama Arifb27c8e62021-06-03 16:44:09 +010071static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080072// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Chris Ye657c2f02021-05-25 16:24:37 -070075static constexpr size_t OBFUSCATED_LENGTH = 8;
76
Chris Ye87143712020-11-10 05:05:58 +000077static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
78static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070079
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070080static constexpr size_t EVENT_BUFFER_SIZE = 256;
81
Chris Yee2b1e5c2021-03-10 22:45:12 -080082// Mapping for input battery class node IDs lookup.
83// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
84static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
85 {{"capacity", InputBatteryClass::CAPACITY},
86 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
87 {"status", InputBatteryClass::STATUS}};
88
89// Mapping for input battery class node names lookup.
90// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
91static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
92 {{InputBatteryClass::CAPACITY, "capacity"},
93 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
94 {InputBatteryClass::STATUS, "status"}};
95
Kim Low03ea0352020-11-06 12:45:07 -080096// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
97static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
98 {{"Unknown", BATTERY_STATUS_UNKNOWN},
99 {"Charging", BATTERY_STATUS_CHARGING},
100 {"Discharging", BATTERY_STATUS_DISCHARGING},
101 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
102 {"Full", BATTERY_STATUS_FULL}};
103
104// Mapping taken from
105// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
106static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
107 {"Low", 10},
108 {"Normal", 55},
109 {"High", 70},
110 {"Full", 100},
111 {"Unknown", 50}};
112
Chris Ye3fdbfef2021-01-06 18:45:18 -0800113// Mapping for input led class node names lookup.
114// https://www.kernel.org/doc/html/latest/leds/leds-class.html
115static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
116 {{"red", InputLightClass::RED},
117 {"green", InputLightClass::GREEN},
118 {"blue", InputLightClass::BLUE},
119 {"global", InputLightClass::GLOBAL},
120 {"brightness", InputLightClass::BRIGHTNESS},
121 {"multi_index", InputLightClass::MULTI_INDEX},
122 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000123 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
124 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800125
126// Mapping for input multicolor led class node names.
127// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
128static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
129 {{InputLightClass::BRIGHTNESS, "brightness"},
130 {InputLightClass::MULTI_INDEX, "multi_index"},
131 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
132
133// Mapping for light color name and the light color
134const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
135 {"green", LightColor::GREEN},
136 {"blue", LightColor::BLUE}};
137
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100138static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700139 SHA_CTX ctx;
140 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100141 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700142 u_char digest[SHA_DIGEST_LENGTH];
143 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800144
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100145 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700146 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100147 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800148 }
149 return out;
150}
151
Prabir Pradhana3621852022-10-14 18:57:23 +0000152/* The set of all Android key codes that correspond to buttons (bit-switches) on a stylus. */
153static constexpr std::array<int32_t, 4> STYLUS_BUTTON_KEYCODES = {
154 AKEYCODE_STYLUS_BUTTON_PRIMARY,
155 AKEYCODE_STYLUS_BUTTON_SECONDARY,
156 AKEYCODE_STYLUS_BUTTON_TERTIARY,
157 AKEYCODE_STYLUS_BUTTON_TAIL,
158};
159
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800160/**
161 * Return true if name matches "v4l-touch*"
162 */
Chris Ye8594e192020-07-14 10:34:06 -0700163static bool isV4lTouchNode(std::string name) {
164 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800165}
166
Philip Quinn39b81682019-01-09 22:20:39 -0800167/**
168 * Returns true if V4L devices should be scanned.
169 *
170 * The system property ro.input.video_enabled can be used to control whether
171 * EventHub scans and opens V4L devices. As V4L does not support multiple
172 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700173 * them.
174 *
175 * Setting this to "false" would prevent any video devices from being discovered and
176 * associated with input devices.
177 *
178 * This property can be used as follows:
179 * 1. To turn off features that are dependent on video device presence.
180 * 2. During testing and development, to allow other clients to read video devices
181 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800182 */
183static bool isV4lScanningEnabled() {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700184 return property_get_bool("ro.input.video_enabled", true /* default_value */);
Philip Quinn39b81682019-01-09 22:20:39 -0800185}
186
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800187static nsecs_t processEventTimestamp(const struct input_event& event) {
188 // Use the time specified in the event instead of the current time
189 // so that downstream code can get more accurate estimates of
190 // event dispatch latency from the time the event is enqueued onto
191 // the evdev client buffer.
192 //
193 // The event's timestamp fortuitously uses the same monotonic clock
194 // time base as the rest of Android. The kernel event device driver
195 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
196 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
197 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
198 // system call that also queries ktime_get_ts().
199
Colin Cross5b799302022-10-18 21:52:41 -0700200 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
201 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800202 return inputEventTime;
203}
204
Kim Low03ea0352020-11-06 12:45:07 -0800205/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000206 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800207 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800208static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800209 std::error_code errorCode;
210
211 // Stat the device path to get the major and minor number of the character file
212 struct stat statbuf;
213 if (stat(devicePath, &statbuf) == -1) {
214 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800215 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800216 }
217
218 unsigned int major_num = major(statbuf.st_rdev);
219 unsigned int minor_num = minor(statbuf.st_rdev);
220
221 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
222 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
223 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
224 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
225
226 // Make sure nothing went wrong in call to canonical()
227 if (errorCode) {
228 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
229 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800230 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800231 }
232
233 // Continue to go up a directory until we reach a directory named "input"
234 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
235 sysfsPath = sysfsPath.parent_path();
236 }
237
238 // Then go up one more and you will be at the sysfs root of the device
239 sysfsPath = sysfsPath.parent_path();
240
241 // Make sure we didn't reach root path and that directory actually exists
242 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
243 if (errorCode) {
244 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
245 errorCode.message().c_str());
246 }
247
248 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800250 }
251
252 return sysfsPath;
253}
254
255/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800256 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800257 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800258static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
259 std::vector<std::filesystem::path> nodes;
260 std::error_code errorCode;
261 auto iter = std::filesystem::directory_iterator(path, errorCode);
262 while (!errorCode && iter != std::filesystem::directory_iterator()) {
263 nodes.push_back(iter->path());
264 iter++;
265 }
266 return nodes;
267}
268
269/**
270 * Returns the list of files under a specified directory in a sysfs path.
271 * Example:
272 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
273 * in the sysfs path.
274 */
275static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
276 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800277 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800278 std::for_each(nodeStr.begin(), nodeStr.end(),
279 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
280 std::vector<std::filesystem::path> nodes;
281 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
282 nodes = allFilesInPath(path / nodeStr);
283 }
284 return nodes;
285}
286
287static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
288 std::filesystem::path path) {
289 std::string indexStr;
290 if (!base::ReadFileToString(path, &indexStr)) {
291 return std::nullopt;
292 }
293
294 // Parse the multi color LED index file, refer to kernel docs
295 // leds/leds-class-multicolor.html
296 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
297 std::smatch results;
298 std::array<LightColor, COLOR_NUM> colors;
299 if (!std::regex_match(indexStr, results, indexPattern)) {
300 return std::nullopt;
301 }
302
303 for (size_t i = 1; i < results.size(); i++) {
304 const auto it = LIGHT_COLORS.find(results[i].str());
305 if (it != LIGHT_COLORS.end()) {
306 // intensities.emplace(it->second, 0);
307 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800308 }
309 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800310 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800311}
312
Prabir Pradhancb42b472022-08-23 16:01:19 +0000313/**
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000314 * Read country code information exposed through the sysfs path.
315 */
316static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
317 // Check the sysfs root path
318 int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
319 std::string str;
320 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
321 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000322 if (hidCountryCode > 35 || hidCountryCode < 0) {
323 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
324 sysfsRootPath.c_str(), hidCountryCode);
325 return InputDeviceCountryCode::INVALID;
326 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000327 }
328
329 return static_cast<InputDeviceCountryCode>(hidCountryCode);
330}
331
332/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000333 * Read information about batteries exposed through the sysfs path.
334 */
335static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
336 const std::filesystem::path& sysfsRootPath) {
337 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
338 int32_t nextBatteryId = 0;
339 // Check if device has any battery.
340 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
341 for (const auto& nodePath : paths) {
342 RawBatteryInfo info;
343 info.id = ++nextBatteryId;
344 info.path = nodePath;
345 info.name = nodePath.filename();
346
347 // Scan the path for all the files
348 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
349 const auto& files = allFilesInPath(nodePath);
350 for (const auto& file : files) {
351 const auto it = BATTERY_CLASSES.find(file.filename().string());
352 if (it != BATTERY_CLASSES.end()) {
353 info.flags |= it->second;
354 }
355 }
356 batteryInfos.insert_or_assign(info.id, info);
357 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
358 }
359 return batteryInfos;
360}
361
362/**
363 * Read information about lights exposed through the sysfs path.
364 */
365static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
366 const std::filesystem::path& sysfsRootPath) {
367 std::unordered_map<int32_t, RawLightInfo> lightInfos;
368 int32_t nextLightId = 0;
369 // Check if device has any lights.
370 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
371 for (const auto& nodePath : paths) {
372 RawLightInfo info;
373 info.id = ++nextLightId;
374 info.path = nodePath;
375 info.name = nodePath.filename();
376 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000377
378 // Light name should follow the naming pattern <name>:<color>:<function>
379 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
380 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
381 std::smatch results;
382
383 if (std::regex_match(info.name, results, indexPattern)) {
384 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
385 // we only care about sections <color> and <function> which will be at index 2 and 3.
386 for (int i = 2; i <= 3; i++) {
387 const auto it = LIGHT_CLASSES.find(results.str(i));
388 if (it != LIGHT_CLASSES.end()) {
389 info.flags |= it->second;
390 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000391 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000392
393 // Set name of the raw light to <function> which represents playerIDs for LEDs that
394 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
395 // player ID logic)
396 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000397 }
398 // Scan the path for all the files
399 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
400 const auto& files = allFilesInPath(nodePath);
401 for (const auto& file : files) {
402 const auto it = LIGHT_CLASSES.find(file.filename().string());
403 if (it != LIGHT_CLASSES.end()) {
404 info.flags |= it->second;
405 // If the node has maximum brightness, read it
406 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
407 std::string str;
408 if (base::ReadFileToString(file, &str)) {
409 info.maxBrightness = std::stoi(str);
410 }
411 }
412 }
413 }
414 lightInfos.insert_or_assign(info.id, info);
415 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
416 }
417 return lightInfos;
418}
419
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420// --- Global Functions ---
421
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700422ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
423 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800424 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700425 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700427 case ABS_X:
428 case ABS_Y:
429 case ABS_PRESSURE:
430 case ABS_TOOL_WIDTH:
431 case ABS_DISTANCE:
432 case ABS_TILT_X:
433 case ABS_TILT_Y:
434 case ABS_MT_SLOT:
435 case ABS_MT_TOUCH_MAJOR:
436 case ABS_MT_TOUCH_MINOR:
437 case ABS_MT_WIDTH_MAJOR:
438 case ABS_MT_WIDTH_MINOR:
439 case ABS_MT_ORIENTATION:
440 case ABS_MT_POSITION_X:
441 case ABS_MT_POSITION_Y:
442 case ABS_MT_TOOL_TYPE:
443 case ABS_MT_BLOB_ID:
444 case ABS_MT_TRACKING_ID:
445 case ABS_MT_PRESSURE:
446 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700447 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 }
449 }
450
Chris Yef59a2f42020-10-16 12:55:26 -0700451 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
452 switch (axis) {
453 case ABS_X:
454 case ABS_Y:
455 case ABS_Z:
456 case ABS_RX:
457 case ABS_RY:
458 case ABS_RZ:
459 return InputDeviceClass::SENSOR;
460 }
461 }
462
Michael Wright842500e2015-03-13 17:32:02 -0700463 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700464 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700465 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700466 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700467 }
468 }
469
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700471 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472}
473
474// --- EventHub::Device ---
475
Prabir Pradhancb42b472022-08-23 16:01:19 +0000476EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
477 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700478 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700479 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000480 path(std::move(path)),
481 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700482 classes(0),
483 configuration(nullptr),
484 virtualKeyMap(nullptr),
485 ffEffectPlaying(false),
486 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000487 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700488 controllerNumber(0),
489 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700490 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491
492EventHub::Device::~Device() {
493 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494}
495
496void EventHub::Device::close() {
497 if (fd >= 0) {
498 ::close(fd);
499 fd = -1;
500 }
501}
502
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700503status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100504 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700505 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100506 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700507 return -errno;
508 }
509 enabled = true;
510 return OK;
511}
512
513status_t EventHub::Device::disable() {
514 close();
515 enabled = false;
516 return OK;
517}
518
Chris Ye989bb932020-07-04 16:18:59 -0700519bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700520 return !isVirtual && enabled;
521}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522
Chris Ye3a1e4462020-08-12 10:13:15 -0700523const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700524 return keyMap.keyCharacterMap;
525}
526
527template <std::size_t N>
528status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
529 if (!hasValidFd()) {
530 return BAD_VALUE;
531 }
532 if ((_IOC_SIZE(ioctlCode) == 0)) {
533 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
534 }
535
536 typename BitArray<N>::Buffer buffer;
537 status_t ret = ioctl(fd, ioctlCode, buffer.data());
538 bitArray.loadFromBuffer(buffer);
539 return ret;
540}
541
542void EventHub::Device::configureFd() {
543 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
544 if (classes.test(InputDeviceClass::KEYBOARD)) {
545 // Disable kernel key repeat since we handle it ourselves
546 unsigned int repeatRate[] = {0, 0};
547 if (ioctl(fd, EVIOCSREP, repeatRate)) {
548 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
549 }
550 }
551
552 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
553 // associated with input events. This is important because the input system
554 // uses the timestamps extensively and assumes they were recorded using the monotonic
555 // clock.
556 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700557 if (classes.test(InputDeviceClass::SENSOR)) {
558 // Each new sensor event should use the same time base as
559 // SystemClock.elapsedRealtimeNanos().
560 clockId = CLOCK_BOOTTIME;
561 }
Chris Ye989bb932020-07-04 16:18:59 -0700562 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
563 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
564}
565
566bool EventHub::Device::hasKeycodeLocked(int keycode) const {
567 if (!keyMap.haveKeyLayout()) {
568 return false;
569 }
570
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700571 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700572 const size_t N = scanCodes.size();
573 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
574 int32_t sc = scanCodes[i];
575 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
576 return true;
577 }
578 }
579
580 return false;
581}
582
583void EventHub::Device::loadConfigurationLocked() {
584 configurationFile =
585 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
586 InputDeviceConfigurationFileType::
587 CONFIGURATION);
588 if (configurationFile.empty()) {
589 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
590 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500591 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
592 PropertyMap::load(configurationFile.c_str());
593 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700594 ALOGE("Error loading input device configuration file for device '%s'. "
595 "Using default configuration.",
596 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500597 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500598 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700599 }
600 }
601}
602
603bool EventHub::Device::loadVirtualKeyMapLocked() {
604 // The virtual key map is supplied by the kernel as a system board property file.
605 std::string propPath = "/sys/board_properties/virtualkeys.";
606 propPath += identifier.getCanonicalName();
607 if (access(propPath.c_str(), R_OK)) {
608 return false;
609 }
610 virtualKeyMap = VirtualKeyMap::load(propPath);
611 return virtualKeyMap != nullptr;
612}
613
614status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500615 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700616}
617
618bool EventHub::Device::isExternalDeviceLocked() {
619 if (configuration) {
620 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700621 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700622 return !value;
623 }
624 }
625 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
626}
627
628bool EventHub::Device::deviceHasMicLocked() {
629 if (configuration) {
630 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700631 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700632 return value;
633 }
634 }
635 return false;
636}
637
638void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
639 int32_t sc;
640 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
641 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700642 ev.input_event_sec = 0;
643 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700644 ev.type = EV_LED;
645 ev.code = sc;
646 ev.value = on ? 1 : 0;
647
648 ssize_t nWrite;
649 do {
650 nWrite = write(fd, &ev, sizeof(struct input_event));
651 } while (nWrite == -1 && errno == EINTR);
652 }
653}
654
655void EventHub::Device::setLedForControllerLocked() {
656 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
657 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
658 }
659}
660
661status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
662 if (!keyMap.haveKeyLayout()) {
663 return NAME_NOT_FOUND;
664 }
665
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700666 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
667 if (scanCode.has_value()) {
668 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
669 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700670 return NO_ERROR;
671 }
672 }
673 return NAME_NOT_FOUND;
674}
675
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100676/**
677 * Get the capabilities for the current process.
678 * Crashes the system if unable to create / check / destroy the capabilities object.
679 */
680class Capabilities final {
681public:
682 explicit Capabilities() {
683 mCaps = cap_get_proc();
684 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
685 }
686
687 /**
688 * Check whether the current process has a specific capability
689 * in the set of effective capabilities.
690 * Return CAP_SET if the process has the requested capability
691 * Return CAP_CLEAR otherwise.
692 */
693 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
694 cap_flag_value_t value;
695 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
696 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
697 return value;
698 }
699
700 ~Capabilities() {
701 const int result = cap_free(mCaps);
702 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
703 }
704
705private:
706 cap_t mCaps;
707};
708
709static void ensureProcessCanBlockSuspend() {
710 Capabilities capabilities;
711 const bool canBlockSuspend =
712 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
713 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
714 "Input must be able to block suspend to properly process events");
715}
716
Michael Wrightd02c5b62014-02-10 15:10:22 -0800717// --- EventHub ---
718
Michael Wrightd02c5b62014-02-10 15:10:22 -0800719const int EventHub::EPOLL_MAX_EVENTS;
720
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700721EventHub::EventHub(void)
722 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
723 mNextDeviceId(1),
724 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700726 mNeedToReopenDevices(false),
727 mNeedToScanDevices(true),
728 mPendingEventCount(0),
729 mPendingEventIndex(0),
730 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100731 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800733 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800734 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800735
Michael Wright8e9a8562022-02-09 13:44:29 +0000736 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000737 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100738
739 std::error_code errorCode;
740 bool isDeviceInotifyAdded = false;
741 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
742 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800743 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100744 addDeviceInotify();
745 isDeviceInotifyAdded = true;
746 if (errorCode) {
747 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
748 errorCode.message().c_str());
749 }
750 }
751
752 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
753 addDeviceInotify();
754 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800755 ALOGI("Video device scanning disabled");
756 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800757
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100758 struct epoll_event eventItem = {};
759 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700760 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800761 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800762 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
763
764 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000765 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800766 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
767
768 mWakeReadPipeFd = wakeFds[0];
769 mWakeWritePipeFd = wakeFds[1];
770
771 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
772 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700773 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774
775 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
776 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700777 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800778
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700779 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800780 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
781 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700782 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800783}
784
785EventHub::~EventHub(void) {
786 closeAllDevicesLocked();
787
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788 ::close(mEpollFd);
789 ::close(mINotifyFd);
790 ::close(mWakeReadPipeFd);
791 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800792}
793
Usama Arifb27c8e62021-06-03 16:44:09 +0100794/**
795 * On devices that don't have any input devices (like some development boards), the /dev/input
796 * directory will be absent. However, the user may still plug in an input device at a later time.
797 * Add watch for contents of /dev/input only when /dev/input appears.
798 */
799void EventHub::addDeviceInputInotify() {
800 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
801 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
802 DEVICE_INPUT_PATH, strerror(errno));
803}
804
805void EventHub::addDeviceInotify() {
806 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
807 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
808 strerror(errno));
809}
810
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000812 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700814 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815}
816
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700817ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000818 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700820 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821}
822
823int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000824 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700826 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827}
828
829void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000830 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800831 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700832 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 *outConfiguration = *device->configuration;
834 } else {
835 outConfiguration->clear();
836 }
837}
838
839status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700840 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 outAxisInfo->clear();
842
843 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000844 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845
846 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700847 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700849 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
850 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
851 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 return -errno;
853 }
854
855 if (info.minimum != info.maximum) {
856 outAxisInfo->valid = true;
857 outAxisInfo->minValue = info.minimum;
858 outAxisInfo->maxValue = info.maximum;
859 outAxisInfo->flat = info.flat;
860 outAxisInfo->fuzz = info.fuzz;
861 outAxisInfo->resolution = info.resolution;
862 }
863 return OK;
864 }
865 }
866 return -1;
867}
868
869bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
870 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000871 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700873 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 }
875 return false;
876}
877
878bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000879 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880
Chris Ye989bb932020-07-04 16:18:59 -0700881 Device* device = getDeviceLocked(deviceId);
882 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
883 ? device->propBitmask.test(property)
884 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885}
886
Chris Yef59a2f42020-10-16 12:55:26 -0700887bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
888 std::scoped_lock _l(mLock);
889
890 Device* device = getDeviceLocked(deviceId);
891 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
892 ? device->mscBitmask.test(mscEvent)
893 : false;
894}
895
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
897 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000898 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899
900 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700901 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
902 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
903 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 }
905 }
906 }
907 return AKEY_STATE_UNKNOWN;
908}
909
910int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000911 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912
913 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700914 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700915 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800916 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700917 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800919 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700920 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800921 return AKEY_STATE_DOWN;
922 }
923 }
924 return AKEY_STATE_UP;
925 }
926 }
927 }
928 return AKEY_STATE_UNKNOWN;
929}
930
Philip Junker4af3b3d2021-12-14 10:36:55 +0100931int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
932 std::scoped_lock _l(mLock);
933
934 Device* device = getDeviceLocked(deviceId);
935 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
936 device->keyMap.keyLayoutMap == nullptr) {
937 return AKEYCODE_UNKNOWN;
938 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700939 std::vector<int32_t> scanCodes =
940 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100941 if (scanCodes.empty()) {
942 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
943 "device %d",
944 locationKeyCode, deviceId);
945 return AKEYCODE_UNKNOWN;
946 }
947 if (scanCodes.size() > 1) {
948 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
949 locationKeyCode);
950 }
951 int32_t outKeyCode;
952 status_t mapKeyRes =
953 device->getKeyCharacterMap()->mapKey(scanCodes[0], 0 /*usageCode*/, &outKeyCode);
954 switch (mapKeyRes) {
955 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000956 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100957 case NAME_NOT_FOUND:
958 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000959 outKeyCode = locationKeyCode;
960 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100961 default:
962 ALOGW("Failed to get key code for key location: Key character map returned error %s",
963 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000964 outKeyCode = AKEYCODE_UNKNOWN;
965 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +0100966 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +0000967 // Remap if there is a Key remapping added to the KCM and return the remapped key
968 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100969}
970
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
972 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000973 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974
975 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700976 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
977 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
978 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 }
980 }
981 }
982 return AKEY_STATE_UNKNOWN;
983}
984
985status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
986 *outValue = 0;
987
988 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000989 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990
991 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700992 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700994 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
995 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
996 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997 return -errno;
998 }
999
1000 *outValue = info.value;
1001 return OK;
1002 }
1003 }
1004 return -1;
1005}
1006
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001007bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001008 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001009 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010
1011 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001012 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001013 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001014 std::vector<int32_t> scanCodes =
1015 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001016
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001017 // check the possible scan codes identified by the layout map against the
1018 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001019 for (const int32_t scanCode : scanCodes) {
1020 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001021 outFlags[codeIndex] = 1;
1022 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023 }
1024 }
1025 }
1026 return true;
1027 }
1028 return false;
1029}
1030
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001031void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1032 std::scoped_lock _l(mLock);
1033 Device* device = getDeviceLocked(deviceId);
1034 if (device == nullptr) {
1035 return;
1036 }
1037 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1038 if (kcm) {
1039 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1040 }
1041}
1042
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001043status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1044 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001047 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048
Chris Ye66fbac32020-07-06 20:36:43 -07001049 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001051 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1052 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1054 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001055 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 }
1057 }
1058
1059 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001060 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001061 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001062 status = NO_ERROR;
1063 }
1064 }
1065
1066 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001067 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001068 // Remap keys based on user-defined key remappings and key behavior defined in the
1069 // corresponding kcm file
1070 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1071
1072 // Remap keys based on Key behavior defined in KCM file
1073 std::tie(*outKeycode, *outMetaState) =
1074 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001075 } else {
1076 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 }
1078 }
1079 }
1080
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001081 if (status != NO_ERROR) {
1082 *outKeycode = 0;
1083 *outFlags = 0;
1084 *outMetaState = metaState;
1085 }
1086
1087 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088}
1089
1090status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001091 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092 Device* device = getDeviceLocked(deviceId);
1093
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001094 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1095 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001096 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001097 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1098 if (!info.has_value()) {
1099 return NAME_NOT_FOUND;
1100 }
1101 *outAxisInfo = *info;
1102 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103}
1104
Chris Yef59a2f42020-10-16 12:55:26 -07001105base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001106 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001107 std::scoped_lock _l(mLock);
1108 Device* device = getDeviceLocked(deviceId);
1109
1110 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1111 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1112 }
1113 return Errorf("Device not found or device has no key layout.");
1114}
1115
Chris Yee2b1e5c2021-03-10 22:45:12 -08001116// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1117// associated with the device ID. Returns an empty map if no miscellaneous device found.
1118const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1119 int32_t deviceId) const {
1120 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1121 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001122 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001123 return EMPTY_BATTERY_INFO;
1124 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001125 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001126}
1127
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001128std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001129 std::scoped_lock _l(mLock);
1130 std::vector<int32_t> batteryIds;
1131
Prabir Pradhan51894782022-08-23 16:29:10 +00001132 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001133 batteryIds.push_back(id);
1134 }
1135
1136 return batteryIds;
1137}
1138
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001139std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1140 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001141 std::scoped_lock _l(mLock);
1142
1143 const auto infos = getBatteryInfoLocked(deviceId);
1144
1145 auto it = infos.find(batteryId);
1146 if (it != infos.end()) {
1147 return it->second;
1148 }
1149
1150 return std::nullopt;
1151}
1152
1153// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001154// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001155const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1156 int32_t deviceId) const {
1157 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1158 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001159 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001160 return EMPTY_LIGHT_INFO;
1161 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001162 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001163}
1164
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001165std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001166 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001167 std::vector<int32_t> lightIds;
1168
Prabir Pradhan51894782022-08-23 16:29:10 +00001169 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001170 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001171 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001172
Chris Ye3fdbfef2021-01-06 18:45:18 -08001173 return lightIds;
1174}
1175
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001176std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001177 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001178
Chris Yee2b1e5c2021-03-10 22:45:12 -08001179 const auto infos = getLightInfoLocked(deviceId);
1180
1181 auto it = infos.find(lightId);
1182 if (it != infos.end()) {
1183 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001184 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001185
Chris Ye3fdbfef2021-01-06 18:45:18 -08001186 return std::nullopt;
1187}
1188
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001189std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001190 std::scoped_lock _l(mLock);
1191
Chris Yee2b1e5c2021-03-10 22:45:12 -08001192 const auto infos = getLightInfoLocked(deviceId);
1193 auto it = infos.find(lightId);
1194 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001195 return std::nullopt;
1196 }
1197 std::string buffer;
1198 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1199 &buffer)) {
1200 return std::nullopt;
1201 }
1202 return std::stoi(buffer);
1203}
1204
1205std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001206 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001207 std::scoped_lock _l(mLock);
1208
Chris Yee2b1e5c2021-03-10 22:45:12 -08001209 const auto infos = getLightInfoLocked(deviceId);
1210 auto lightIt = infos.find(lightId);
1211 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001212 return std::nullopt;
1213 }
1214
1215 auto ret =
1216 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1217
1218 if (!ret.has_value()) {
1219 return std::nullopt;
1220 }
1221 std::array<LightColor, COLOR_NUM> colors = ret.value();
1222
1223 std::string intensityStr;
1224 if (!base::ReadFileToString(lightIt->second.path /
1225 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1226 &intensityStr)) {
1227 return std::nullopt;
1228 }
1229
1230 // Intensity node outputs 3 color values
1231 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1232 std::smatch results;
1233
1234 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1235 return std::nullopt;
1236 }
1237 std::unordered_map<LightColor, int32_t> intensities;
1238 for (size_t i = 1; i < results.size(); i++) {
1239 int value = std::stoi(results[i].str());
1240 intensities.emplace(colors[i - 1], value);
1241 }
1242 return intensities;
1243}
1244
1245void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1246 std::scoped_lock _l(mLock);
1247
Chris Yee2b1e5c2021-03-10 22:45:12 -08001248 const auto infos = getLightInfoLocked(deviceId);
1249 auto lightIt = infos.find(lightId);
1250 if (lightIt == infos.end()) {
1251 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001252 return;
1253 }
1254
1255 if (!base::WriteStringToFile(std::to_string(brightness),
1256 lightIt->second.path /
1257 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1258 ALOGE("Can not write to file, error: %s", strerror(errno));
1259 }
1260}
1261
1262void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1263 std::unordered_map<LightColor, int32_t> intensities) {
1264 std::scoped_lock _l(mLock);
1265
Chris Yee2b1e5c2021-03-10 22:45:12 -08001266 const auto infos = getLightInfoLocked(deviceId);
1267 auto lightIt = infos.find(lightId);
1268 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001269 ALOGE("Light Id %d does not exist.", lightId);
1270 return;
1271 }
1272
1273 auto ret =
1274 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1275
1276 if (!ret.has_value()) {
1277 return;
1278 }
1279 std::array<LightColor, COLOR_NUM> colors = ret.value();
1280
1281 std::string rgbStr;
1282 for (size_t i = 0; i < COLOR_NUM; i++) {
1283 auto it = intensities.find(colors[i]);
1284 if (it != intensities.end()) {
1285 rgbStr += std::to_string(it->second);
1286 // Insert space between colors
1287 if (i < COLOR_NUM - 1) {
1288 rgbStr += " ";
1289 }
1290 }
1291 }
1292 // Append new line
1293 rgbStr += "\n";
1294
1295 if (!base::WriteStringToFile(rgbStr,
1296 lightIt->second.path /
1297 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1298 ALOGE("Can not write to file, error: %s", strerror(errno));
1299 }
1300}
1301
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001302InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
1303 std::scoped_lock _l(mLock);
1304 Device* device = getDeviceLocked(deviceId);
1305 if (device == nullptr || !device->associatedDevice) {
1306 return InputDeviceCountryCode::INVALID;
1307 }
1308 return device->associatedDevice->countryCode;
1309}
1310
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001311void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001312 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001313
1314 mExcludedDevices = devices;
1315}
1316
1317bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001318 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001319 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001320 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1321 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001322 }
1323 return false;
1324}
1325
Arthur Hungcb40a002021-08-03 14:31:01 +00001326bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1327 std::scoped_lock _l(mLock);
1328 Device* device = getDeviceLocked(deviceId);
1329 if (device != nullptr) {
1330 return device->hasKeycodeLocked(keyCode);
1331 }
1332 return false;
1333}
1334
Michael Wrightd02c5b62014-02-10 15:10:22 -08001335bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001336 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001337 Device* device = getDeviceLocked(deviceId);
1338 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001339 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001340 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 }
1342 return false;
1343}
1344
1345void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001346 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001347 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001348 if (device != nullptr && device->hasValidFd()) {
1349 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001350 }
1351}
1352
1353void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001354 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001355 outVirtualKeys.clear();
1356
Chris Ye87143712020-11-10 05:05:58 +00001357 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001358 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001359 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001360 const std::vector<VirtualKeyDefinition> virtualKeys =
1361 device->virtualKeyMap->getVirtualKeys();
1362 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001363 }
1364}
1365
Chris Ye3a1e4462020-08-12 10:13:15 -07001366const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001367 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001368 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001369 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001370 return device->getKeyCharacterMap();
1371 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001372 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001373}
1374
Chris Ye3a1e4462020-08-12 10:13:15 -07001375bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001376 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001377 Device* device = getDeviceLocked(deviceId);
Philip Junker90bc9492021-12-10 18:39:42 +01001378 if (device == nullptr || map == nullptr || device->keyMap.keyCharacterMap == nullptr) {
1379 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001380 }
Philip Junker90bc9492021-12-10 18:39:42 +01001381 device->keyMap.keyCharacterMap->combine(*map);
1382 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001383}
1384
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001385static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1386 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001387 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001389 if (!identifier.uniqueId.empty()) {
1390 rawDescriptor += "uniqueId:";
1391 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001392 }
1393 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001394 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001395 }
1396
1397 if (identifier.vendor == 0 && identifier.product == 0) {
1398 // If we don't know the vendor and product id, then the device is probably
1399 // built-in so we need to rely on other information to uniquely identify
1400 // the input device. Usually we try to avoid relying on the device name or
1401 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001402 if (!identifier.name.empty()) {
1403 rawDescriptor += "name:";
1404 rawDescriptor += identifier.name;
1405 } else if (!identifier.location.empty()) {
1406 rawDescriptor += "location:";
1407 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 }
1409 }
1410 identifier.descriptor = sha1(rawDescriptor);
1411 return rawDescriptor;
1412}
1413
1414void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1415 // Compute a device descriptor that uniquely identifies the device.
1416 // The descriptor is assumed to be a stable identifier. Its value should not
1417 // change between reboots, reconnections, firmware updates or new releases
1418 // of Android. In practice we sometimes get devices that cannot be uniquely
1419 // identified. In this case we enforce uniqueness between connected devices.
1420 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001421 // Note that we explicitly do not use the path or location for external devices
1422 // as their path or location will change as they are plugged/unplugged or moved
1423 // to different ports. We do fallback to using name and location in the case of
1424 // internal devices which are detected by the vendor and product being 0 in
1425 // generateDescriptor. If two identical descriptors are detected we will fallback
1426 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1427 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001428
1429 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001430 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001431 // Enforce that the generated descriptor is unique.
1432 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1433 identifier.nonce++;
1434 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001435 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001436 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001437 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001438}
1439
Prabir Pradhancb42b472022-08-23 16:01:19 +00001440std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1441 const std::filesystem::path& devicePath) const {
1442 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1443 getSysfsRootPath(devicePath.c_str());
1444 if (!sysfsRootPathOpt) {
1445 return nullptr;
1446 }
1447
1448 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001449
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001450 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001451 AssociatedDevice{.sysfsRootPath = path,
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001452 .countryCode = readCountryCodeLocked(path),
Prabir Pradhancb42b472022-08-23 16:01:19 +00001453 .batteryInfos = readBatteryConfiguration(path),
1454 .lightInfos = readLightsConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001455
1456 bool associatedDeviceChanged = false;
1457 for (const auto& [id, dev] : mDevices) {
1458 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1459 if (*associatedDevice != *dev->associatedDevice) {
1460 associatedDeviceChanged = true;
1461 dev->associatedDevice = associatedDevice;
1462 }
1463 associatedDevice = dev->associatedDevice;
1464 }
1465 }
1466 ALOGI_IF(associatedDeviceChanged,
1467 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1468 path.c_str(), associatedDevice->dump().c_str());
1469
1470 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001471}
1472
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001473void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001474 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001475 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001476 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001477 ff_effect effect;
1478 memset(&effect, 0, sizeof(effect));
1479 effect.type = FF_RUMBLE;
1480 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001481 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001482 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1483 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001484 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 effect.replay.delay = 0;
1486 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1487 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001488 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 return;
1490 }
1491 device->ffEffectId = effect.id;
1492
1493 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001494 ev.input_event_sec = 0;
1495 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 ev.type = EV_FF;
1497 ev.code = device->ffEffectId;
1498 ev.value = 1;
1499 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1500 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001501 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001502 return;
1503 }
1504 device->ffEffectPlaying = true;
1505 }
1506}
1507
1508void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001509 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001510 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001511 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001512 if (device->ffEffectPlaying) {
1513 device->ffEffectPlaying = false;
1514
1515 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001516 ev.input_event_sec = 0;
1517 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518 ev.type = EV_FF;
1519 ev.code = device->ffEffectId;
1520 ev.value = 0;
1521 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1522 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001523 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001524 return;
1525 }
1526 }
1527 }
1528}
1529
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001530std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001531 std::scoped_lock _l(mLock);
1532 std::vector<int32_t> vibrators;
1533 Device* device = getDeviceLocked(deviceId);
1534 if (device != nullptr && device->hasValidFd() &&
1535 device->classes.test(InputDeviceClass::VIBRATOR)) {
1536 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1537 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1538 }
1539 return vibrators;
1540}
1541
Josh Bartel938632f2022-07-19 15:34:22 -05001542/**
1543 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1544 */
1545bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1546 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001547 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001548 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 }
Josh Bartel938632f2022-07-19 15:34:22 -05001551
1552 for (const auto& [id, device] : mDevices) {
1553 if (descriptor == device->identifier.descriptor) {
1554 return true;
1555 }
1556 }
1557 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558}
1559
1560EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001561 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001562 deviceId = mBuiltInKeyboardId;
1563 }
Chris Ye989bb932020-07-04 16:18:59 -07001564 const auto& it = mDevices.find(deviceId);
1565 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001566}
1567
Chris Ye8594e192020-07-14 10:34:06 -07001568EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001569 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001570 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001571 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001572 }
1573 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001574 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001575}
1576
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001577/**
1578 * The file descriptor could be either input device, or a video device (associated with a
1579 * specific input device). Check both cases here, and return the device that this event
1580 * belongs to. Caller can compare the fd's once more to determine event type.
1581 * Looks through all input devices, and only attached video devices. Unattached video
1582 * devices are ignored.
1583 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001584EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001585 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001586 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001587 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001588 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001589 }
1590 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1591 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001592 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001593 }
1594 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001595 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1596 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001597 return nullptr;
1598}
1599
Chris Yee2b1e5c2021-03-10 22:45:12 -08001600std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001601 std::filesystem::path batteryPath;
1602 {
1603 // Do not read the sysfs node to get the battery state while holding
1604 // the EventHub lock. For some peripheral devices, reading battery state
1605 // can be broken and take 5+ seconds. Holding the lock in this case would
1606 // block all other event processing during this time. For now, we assume this
1607 // call never happens on the InputReader thread and read the sysfs node outside
1608 // the lock to prevent event processing from being blocked by this call.
1609 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001610
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001611 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001612 auto it = infos.find(batteryId);
1613 if (it == infos.end()) {
1614 return std::nullopt;
1615 }
1616 batteryPath = it->second.path;
1617 } // release lock
1618
Chris Yee2b1e5c2021-03-10 22:45:12 -08001619 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001620
1621 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001622 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001623 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001624 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001625 }
1626
1627 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1628 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001629 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001630 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001631 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001632 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1633 if (levelIt != BATTERY_LEVEL.end()) {
1634 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001635 }
1636 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001637
Kim Low03ea0352020-11-06 12:45:07 -08001638 return std::nullopt;
1639}
1640
Chris Yee2b1e5c2021-03-10 22:45:12 -08001641std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001642 std::filesystem::path batteryPath;
1643 {
1644 // Do not read the sysfs node to get the battery state while holding
1645 // the EventHub lock. For some peripheral devices, reading battery state
1646 // can be broken and take 5+ seconds. Holding the lock in this case would
1647 // block all other event processing during this time. For now, we assume this
1648 // call never happens on the InputReader thread and read the sysfs node outside
1649 // the lock to prevent event processing from being blocked by this call.
1650 std::scoped_lock _l(mLock);
1651
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001652 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001653 auto it = infos.find(batteryId);
1654 if (it == infos.end()) {
1655 return std::nullopt;
1656 }
1657 batteryPath = it->second.path;
1658 } // release lock
1659
Chris Yee2b1e5c2021-03-10 22:45:12 -08001660 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001661
Andy Chenf9f1a022022-08-29 20:07:10 -04001662 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001663 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001664 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1665 return std::nullopt;
1666 }
1667
Chris Yed1936772021-02-22 10:30:40 -08001668 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001669 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1670 if (statusIt != BATTERY_STATUS.end()) {
1671 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001672 }
1673
1674 return std::nullopt;
1675}
1676
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001677std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001678 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001679
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001680 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001681
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001682 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001683 bool awoken = false;
1684 for (;;) {
1685 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1686
1687 // Reopen input devices if needed.
1688 if (mNeedToReopenDevices) {
1689 mNeedToReopenDevices = false;
1690
1691 ALOGI("Reopening all input devices due to a configuration change.");
1692
1693 closeAllDevicesLocked();
1694 mNeedToScanDevices = true;
1695 break; // return to the caller before we actually rescan
1696 }
1697
1698 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001699 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1700 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001701 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001702 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001703 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1704 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001705 events.push_back({
1706 .when = now,
1707 .deviceId = deviceId,
1708 .type = DEVICE_REMOVED,
1709 });
Chris Ye989bb932020-07-04 16:18:59 -07001710 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001712 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 break;
1714 }
1715 }
1716
1717 if (mNeedToScanDevices) {
1718 mNeedToScanDevices = false;
1719 scanDevicesLocked();
1720 mNeedToSendFinishedDeviceScan = true;
1721 }
1722
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001723 while (!mOpeningDevices.empty()) {
1724 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1725 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001726 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001727 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1728 events.push_back({
1729 .when = now,
1730 .deviceId = deviceId,
1731 .type = DEVICE_ADDED,
1732 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001733
1734 // Try to find a matching video device by comparing device names
1735 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1736 it++) {
1737 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001738 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001739 // videoDevice was transferred to 'device'
1740 it = mUnattachedVideoDevices.erase(it);
1741 break;
1742 }
1743 }
1744
1745 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1746 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001747 ALOGW("Device id %d exists, replaced.", device->id);
1748 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001749 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001750 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751 break;
1752 }
1753 }
1754
1755 if (mNeedToSendFinishedDeviceScan) {
1756 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001757 events.push_back({
1758 .when = now,
1759 .type = FINISHED_DEVICE_SCAN,
1760 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001761 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001762 break;
1763 }
1764 }
1765
1766 // Grab the next input event.
1767 bool deviceChanged = false;
1768 while (mPendingEventIndex < mPendingEventCount) {
1769 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001770 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 if (eventItem.events & EPOLLIN) {
1772 mPendingINotify = true;
1773 } else {
1774 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1775 }
1776 continue;
1777 }
1778
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001779 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 if (eventItem.events & EPOLLIN) {
1781 ALOGV("awoken after wake()");
1782 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001783 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001784 ssize_t nRead;
1785 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001786 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1787 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001788 } else {
1789 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001790 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 }
1792 continue;
1793 }
1794
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001795 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001796 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001797 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1798 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001799 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001800 continue;
1801 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001802 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1803 if (eventItem.events & EPOLLIN) {
1804 size_t numFrames = device->videoDevice->readAndQueueFrames();
1805 if (numFrames == 0) {
1806 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001807 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001808 }
1809 } else if (eventItem.events & EPOLLHUP) {
1810 // TODO(b/121395353) - consider adding EPOLLRDHUP
1811 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001812 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001813 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1814 device->videoDevice = nullptr;
1815 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001816 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1817 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001818 ALOG_ASSERT(!DEBUG);
1819 }
1820 continue;
1821 }
1822 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001824 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001825 read(device->fd, readBuffer.data(),
1826 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001827 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1828 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001829 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001830 " capacity: %zu errno: %d)\n",
1831 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001833 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 } else if (readSize < 0) {
1835 if (errno != EAGAIN && errno != EINTR) {
1836 ALOGW("could not get event (errno=%d)", errno);
1837 }
1838 } else if ((readSize % sizeof(struct input_event)) != 0) {
1839 ALOGE("could not get event (wrong size: %d)", readSize);
1840 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001841 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001842
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001843 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001844 for (size_t i = 0; i < count; i++) {
1845 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001846 events.push_back({
1847 .when = processEventTimestamp(iev),
1848 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1849 .deviceId = deviceId,
1850 .type = iev.type,
1851 .code = iev.code,
1852 .value = iev.value,
1853 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001854 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001855 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 // The result buffer is full. Reset the pending event index
1857 // so we will try to read the device again on the next iteration.
1858 mPendingEventIndex -= 1;
1859 break;
1860 }
1861 }
1862 } else if (eventItem.events & EPOLLHUP) {
1863 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001864 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001865 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001866 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001867 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1869 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001870 }
1871 }
1872
1873 // readNotify() will modify the list of devices so this must be done after
1874 // processing all other events to ensure that we read all remaining events
1875 // before closing the devices.
1876 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1877 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001878 const auto res = readNotifyLocked();
1879 if (!res.ok()) {
1880 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1881 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001882 deviceChanged = true;
1883 }
1884
1885 // Report added or removed devices immediately.
1886 if (deviceChanged) {
1887 continue;
1888 }
1889
1890 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001891 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001892 break;
1893 }
1894
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001895 // Poll for events.
1896 // When a device driver has pending (unread) events, it acquires
1897 // a kernel wake lock. Once the last pending event has been read, the device
1898 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1899 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1900 // is called again for the same fd that produced the event.
1901 // Thus the system can only sleep if there are no events pending or
1902 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903 //
1904 // The timeout is advisory only. If the device is asleep, it will not wake just to
1905 // service the timeout.
1906 mPendingEventIndex = 0;
1907
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001908 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001909
1910 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1911
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001912 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913
1914 if (pollResult == 0) {
1915 // Timed out.
1916 mPendingEventCount = 0;
1917 break;
1918 }
1919
1920 if (pollResult < 0) {
1921 // An error occurred.
1922 mPendingEventCount = 0;
1923
1924 // Sleep after errors to avoid locking up the system.
1925 // Hopefully the error is transient.
1926 if (errno != EINTR) {
1927 ALOGW("poll failed (errno=%d)\n", errno);
1928 usleep(100000);
1929 }
1930 } else {
1931 // Some events occurred.
1932 mPendingEventCount = size_t(pollResult);
1933 }
1934 }
1935
1936 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001937 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001940std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001941 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001942
1943 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001944 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08001945 return {};
1946 }
1947 return device->videoDevice->consumeFrames();
1948}
1949
Michael Wrightd02c5b62014-02-10 15:10:22 -08001950void EventHub::wake() {
1951 ALOGV("wake() called");
1952
1953 ssize_t nWrite;
1954 do {
1955 nWrite = write(mWakeWritePipeFd, "W", 1);
1956 } while (nWrite == -1 && errno == EINTR);
1957
1958 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001959 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001960 }
1961}
1962
1963void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01001964 status_t result;
1965 std::error_code errorCode;
1966
1967 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
1968 result = scanDirLocked(DEVICE_INPUT_PATH);
1969 if (result < 0) {
1970 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
1971 }
1972 } else {
1973 if (errorCode) {
1974 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
1975 errorCode.message().c_str());
1976 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08001977 }
Philip Quinn39b81682019-01-09 22:20:39 -08001978 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001979 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001980 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01001981 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08001982 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001983 }
Chris Ye989bb932020-07-04 16:18:59 -07001984 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 createVirtualKeyboardLocked();
1986 }
1987}
1988
1989// ----------------------------------------------------------------------------
1990
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001992 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
1993 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
1994 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
1995 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
1996 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
1997 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998};
1999
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002000status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002001 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002002 struct epoll_event eventItem = {};
2003 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2004 eventItem.data.fd = fd;
2005 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2006 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002007 return -errno;
2008 }
2009 return OK;
2010}
2011
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002012status_t EventHub::unregisterFdFromEpoll(int fd) {
2013 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2014 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2015 return -errno;
2016 }
2017 return OK;
2018}
2019
Chris Ye989bb932020-07-04 16:18:59 -07002020status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2021 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002022 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002023 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002024 return result;
2025 }
Chris Ye989bb932020-07-04 16:18:59 -07002026 if (device.videoDevice) {
2027 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002028 }
2029 return result;
2030}
2031
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002032void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2033 status_t result = registerFdForEpoll(videoDevice.getFd());
2034 if (result != OK) {
2035 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2036 }
2037}
2038
Chris Ye989bb932020-07-04 16:18:59 -07002039status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2040 if (device.hasValidFd()) {
2041 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002042 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002043 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002044 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002045 }
2046 }
Chris Ye989bb932020-07-04 16:18:59 -07002047 if (device.videoDevice) {
2048 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002049 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002050 return OK;
2051}
2052
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002053void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2054 if (videoDevice.hasValidFd()) {
2055 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2056 if (result != OK) {
2057 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002058 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002059 }
2060 }
2061}
2062
Chris Yed3fef462021-03-07 17:10:08 -08002063void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002064 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002065 SHA256_CTX ctx;
2066 SHA256_Init(&ctx);
2067 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2068 identifier.uniqueId.size());
2069 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2070 SHA256_Final(digest.data(), &ctx);
2071
2072 std::string obfuscatedId;
2073 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2074 obfuscatedId += StringPrintf("%02x", digest[i]);
2075 }
2076
Chris Yed3fef462021-03-07 17:10:08 -08002077 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2078 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002079 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002080}
2081
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002082void EventHub::openDeviceLocked(const std::string& devicePath) {
2083 // If an input device happens to register around the time when EventHub's constructor runs, it
2084 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2085 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2086 // from getting registered, ensure that this path is not already covered by an existing device.
2087 for (const auto& [deviceId, device] : mDevices) {
2088 if (device->path == devicePath) {
2089 return; // device was already registered
2090 }
2091 }
2092
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 char buffer[80];
2094
Chris Ye8594e192020-07-14 10:34:06 -07002095 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096
Chris Ye8594e192020-07-14 10:34:06 -07002097 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002098 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002099 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002100 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 }
2102
2103 InputDeviceIdentifier identifier;
2104
2105 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002106 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002107 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 } else {
2109 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002110 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002111 }
2112
2113 // Check to see if the device is on our excluded list
2114 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002115 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002116 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002117 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002118 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002119 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120 }
2121 }
2122
2123 // Get device driver version.
2124 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002125 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002126 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002128 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002129 }
2130
2131 // Get device identifier.
2132 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002133 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002134 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002136 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 }
2138 identifier.bus = inputId.bustype;
2139 identifier.product = inputId.product;
2140 identifier.vendor = inputId.vendor;
2141 identifier.version = inputId.version;
2142
2143 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002144 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2145 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002146 } else {
2147 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002148 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002149 }
2150
2151 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002152 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2153 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 } else {
2155 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002156 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157 }
2158
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002159 // Attempt to get the bluetooth address of an input device from the uniqueId.
2160 if (identifier.bus == BUS_BLUETOOTH &&
2161 std::regex_match(identifier.uniqueId,
2162 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2163 identifier.bluetoothAddress = identifier.uniqueId;
2164 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2165 for (auto& c : *identifier.bluetoothAddress) {
2166 c = ::toupper(c);
2167 }
2168 }
2169
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170 // Fill in the descriptor.
2171 assignDescriptorLocked(identifier);
2172
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 // Allocate device. (The device object takes ownership of the fd at this point.)
2174 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002175 std::unique_ptr<Device> device =
2176 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2177 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178
Chris Ye8594e192020-07-14 10:34:06 -07002179 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002181 " vendor %04x\n"
2182 " product %04x\n"
2183 " version %04x\n",
2184 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002185 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2186 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2187 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2188 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002189 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2190 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191
2192 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002193 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002194
2195 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002196 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2197 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2198 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2199 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2200 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2201 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002202 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002203 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002204
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002205 // See if this is a device with keys. This could be full keyboard, or other devices like
2206 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002207 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002208 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2209 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2210 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002211 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2212 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2213 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002214 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 }
2216
2217 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002218 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2219 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002220 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
Prabir Pradhana3621852022-10-14 18:57:23 +00002223 // See if the device is specially configured to be of a certain type.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002224 std::string deviceType;
2225 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2226 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002227 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002228 } else if (deviceType == "externalStylus") {
2229 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002230 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002231 }
2232
Michael Wrightd02c5b62014-02-10 15:10:22 -08002233 // See if this is a touch pad.
2234 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002235 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236 // Some joysticks such as the PS3 controller report axes that conflict
2237 // with the ABS_MT range. Try to confirm that the device really is
2238 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002239 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002240 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002241 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2242 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2243 device->classes |= InputDeviceClass::TOUCHPAD;
2244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002246 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002247 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2248 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002249 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002250 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002251 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2252 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002253 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
2255
2256 // See if this device is a joystick.
2257 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2258 // from other devices such as accelerometers that also have absolute axes.
2259 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002260 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002262 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002263 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 device->classes = assumedClasses;
2265 break;
2266 }
2267 }
2268 }
2269
Chris Yef59a2f42020-10-16 12:55:26 -07002270 // Check whether this device is an accelerometer.
2271 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2272 device->classes |= InputDeviceClass::SENSOR;
2273 }
2274
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 // Check whether this device has switches.
2276 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002277 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002278 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 break;
2280 }
2281 }
2282
2283 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002284 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002285 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 }
2287
2288 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002289 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 // Load the virtual keys for the touch screen, if any.
2291 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002292 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002293 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002294 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296 }
2297
2298 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002299 // We need to do this for joysticks too because the key layout may specify axes, and for
2300 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002302 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2303 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002305 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307
2308 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002309 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002311 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002312 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2313 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 mBuiltInKeyboardId = device->id;
2315 }
2316
2317 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002318 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002319 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002320 }
2321
2322 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002323 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2324 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2325 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2326 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2327 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002328 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 }
2330
2331 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002332 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002333 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002334 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002335 break;
2336 }
2337 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002338
2339 // See if this device has any stylus buttons that we would want to fuse with touch data.
2340 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2341 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2342 if (device->hasKeycodeLocked(keycode)) {
2343 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2344 break;
2345 }
2346 }
2347 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002348 }
2349
2350 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002351 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002352 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002353 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002354 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002355 }
2356
Chris Ye3fdbfef2021-01-06 18:45:18 -08002357 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002358 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002359 device->classes |= InputDeviceClass::BATTERY;
2360 }
Kim Low03ea0352020-11-06 12:45:07 -08002361
Chris Ye3fdbfef2021-01-06 18:45:18 -08002362 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002363 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002364 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002365 }
2366
Tim Kilbourn063ff532015-04-08 10:26:18 -07002367 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002368 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002369 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002370 }
2371
Michael Wrightd02c5b62014-02-10 15:10:22 -08002372 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002373 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002374 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
Chris Ye1b0c7342020-07-28 21:57:03 -07002377 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2378 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002379 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2380 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
Chris Ye989bb932020-07-04 16:18:59 -07002383 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002384 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002385 }
2386
Chris Ye989bb932020-07-04 16:18:59 -07002387 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002388
Chris Ye1b0c7342020-07-28 21:57:03 -07002389 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002390 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002391 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2392 device->classes.string().c_str(), device->configurationFile.c_str(),
2393 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2394 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002395
Chris Ye989bb932020-07-04 16:18:59 -07002396 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002397}
2398
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002399void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2400 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2401 if (!videoDevice) {
2402 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2403 return;
2404 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002405 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002406 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002407 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002408 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002409 }
2410 }
2411
2412 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2413 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002414 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002415 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002416 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2417}
2418
Chris Yed3fef462021-03-07 17:10:08 -08002419bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2420 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002421 if (videoDevice->getName() != device.identifier.name) {
2422 return false;
2423 }
2424 device.videoDevice = std::move(videoDevice);
2425 if (device.enabled) {
2426 registerVideoDeviceForEpollLocked(*device.videoDevice);
2427 }
2428 return true;
2429}
2430
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002431bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002432 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002433 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002434 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002435 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2436 return false;
2437 }
2438 return device->enabled;
2439}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002440
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002441status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002442 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002443 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002444 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002445 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2446 return BAD_VALUE;
2447 }
2448 if (device->enabled) {
2449 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2450 return OK;
2451 }
2452 status_t result = device->enable();
2453 if (result != OK) {
2454 ALOGE("Failed to enable device %" PRId32, deviceId);
2455 return result;
2456 }
2457
Chris Ye989bb932020-07-04 16:18:59 -07002458 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002459
Chris Ye989bb932020-07-04 16:18:59 -07002460 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002461}
2462
2463status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002464 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002465 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002466 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002467 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2468 return BAD_VALUE;
2469 }
2470 if (!device->enabled) {
2471 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2472 return OK;
2473 }
Chris Ye989bb932020-07-04 16:18:59 -07002474 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002475 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476}
2477
2478void EventHub::createVirtualKeyboardLocked() {
2479 InputDeviceIdentifier identifier;
2480 identifier.name = "Virtual";
2481 identifier.uniqueId = "<virtual>";
2482 assignDescriptorLocked(identifier);
2483
Chris Ye989bb932020-07-04 16:18:59 -07002484 std::unique_ptr<Device> device =
2485 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Prabir Pradhancb42b472022-08-23 16:01:19 +00002486 identifier, nullptr /*associatedDevice*/);
Chris Ye1b0c7342020-07-28 21:57:03 -07002487 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2488 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002489 device->loadKeyMapLocked();
2490 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491}
2492
Chris Ye989bb932020-07-04 16:18:59 -07002493void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002494 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002495 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002496}
2497
Chris Ye989bb932020-07-04 16:18:59 -07002498int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002499 if (mControllerNumbers.isFull()) {
2500 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002501 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002502 return 0;
2503 }
2504 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2505 // one
2506 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2507}
2508
Chris Ye989bb932020-07-04 16:18:59 -07002509void EventHub::releaseControllerNumberLocked(int32_t num) {
2510 if (num > 0) {
2511 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002513}
2514
Chris Ye8594e192020-07-14 10:34:06 -07002515void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002516 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002517 if (device != nullptr) {
2518 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002519 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002520 }
Chris Ye8594e192020-07-14 10:34:06 -07002521 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002522}
2523
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002524/**
2525 * Find the video device by filename, and close it.
2526 * The video device is closed by path during an inotify event, where we don't have the
2527 * additional context about the video device fd, or the associated input device.
2528 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002529void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002530 // A video device may be owned by an existing input device, or it may be stored in
2531 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002532 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002533 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002534 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002535 device->videoDevice = nullptr;
2536 return;
2537 }
2538 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002539 std::erase_if(mUnattachedVideoDevices,
2540 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2541 return videoDevice->getPath() == devicePath;
2542 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002543}
2544
2545void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002546 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002547 while (!mDevices.empty()) {
2548 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 }
2550}
2551
Chris Ye989bb932020-07-04 16:18:59 -07002552void EventHub::closeDeviceLocked(Device& device) {
2553 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2554 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555
Chris Ye989bb932020-07-04 16:18:59 -07002556 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002558 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2560 }
2561
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002562 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002563 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002564 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002565 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002566 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567
Chris Ye989bb932020-07-04 16:18:59 -07002568 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002569 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002570 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002571 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002572
Chris Ye989bb932020-07-04 16:18:59 -07002573 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574}
2575
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002576base::Result<void> EventHub::readNotifyLocked() {
2577 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2578 uint8_t eventBuffer[512];
2579 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
2581 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002582 do {
2583 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2584 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002585
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002586 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2587
2588 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2589 const inotify_event* event;
2590 event = (const inotify_event*)(eventBuffer + eventPos);
2591 if (event->len == 0) continue;
2592
2593 handleNotifyEventLocked(*event);
2594
2595 const ssize_t eventSize = EVENT_SIZE + event->len;
2596 sizeRead -= eventSize;
2597 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002598 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002599 return {};
2600}
2601
2602void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2603 if (event.wd == mDeviceInputWd) {
2604 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2605 if (event.mask & IN_CREATE) {
2606 openDeviceLocked(filename);
2607 } else {
2608 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2609 closeDeviceByPathLocked(filename);
2610 }
2611 } else if (event.wd == mDeviceWd) {
2612 if (isV4lTouchNode(event.name)) {
2613 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2614 if (event.mask & IN_CREATE) {
2615 openVideoDeviceLocked(filename);
2616 } else {
2617 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2618 closeVideoDeviceByPathLocked(filename);
2619 }
2620 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2621 addDeviceInputInotify();
2622 }
2623 } else {
2624 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2625 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626}
2627
Chris Ye8594e192020-07-14 10:34:06 -07002628status_t EventHub::scanDirLocked(const std::string& dirname) {
2629 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2630 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002631 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002632 return 0;
2633}
2634
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002635/**
2636 * Look for all dirname/v4l-touch* devices, and open them.
2637 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002638status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002639 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2640 if (isV4lTouchNode(entry.path())) {
2641 ALOGI("Found touch video device %s", entry.path().c_str());
2642 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002643 }
2644 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002645 return OK;
2646}
2647
Michael Wrightd02c5b62014-02-10 15:10:22 -08002648void EventHub::requestReopenDevices() {
2649 ALOGV("requestReopenDevices() called");
2650
Chris Ye87143712020-11-10 05:05:58 +00002651 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002652 mNeedToReopenDevices = true;
2653}
2654
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002655void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002656 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657
2658 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002659 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002661 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002663 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002664
Chris Ye989bb932020-07-04 16:18:59 -07002665 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002667 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002668 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002670 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002671 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002673 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002674 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002675 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002676 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2677 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002678 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002679 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002680 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002681 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002682 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002683 device->identifier.product, device->identifier.version,
2684 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002685 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002686 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002687 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002688 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00002689 dump += StringPrintf(INDENT3 "CountryCode: %d\n",
2690 device->associatedDevice ? device->associatedDevice->countryCode
2691 : InputDeviceCountryCode::INVALID);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002692 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002693 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002694 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2695 device->videoDevice ? device->videoDevice->dump().c_str()
2696 : "<none>");
2697 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2698 device->associatedDevice
2699 ? device->associatedDevice->sysfsRootPath.c_str()
2700 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002702
2703 dump += INDENT "Unattached video devices:\n";
2704 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2705 dump += INDENT2 + videoDevice->dump() + "\n";
2706 }
2707 if (mUnattachedVideoDevices.empty()) {
2708 dump += INDENT2 "<none>\n";
2709 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002710 } // release lock
2711}
2712
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002713void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002715 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002716}
2717
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002718std::string EventHub::AssociatedDevice::dump() const {
2719 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2720 batteryInfos.size(), lightInfos.size());
2721}
2722
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002723} // namespace android