blob: 035416415523f6c2d7125303c06706ff9f713aa9 [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>
Harry Cuttsf13161a2023-03-08 14:15:49 +000055#include <optional>
Chris Ye3fdbfef2021-01-06 18:45:18 -080056#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000057#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070058
59#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
Michael Wrightd02c5b62014-02-10 15:10:22 -080061#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080065using android::base::StringPrintf;
66
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
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000138// Mapping for country code to Layout info.
139// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
140const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
141 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
142 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
143 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
144 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
145 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
146 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
147 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
148 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
149 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
150 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
151 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
152 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
153 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
154 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
155 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
156 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
157 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
158 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
159 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
160 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
161 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
162 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
163 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
164 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
165 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
166 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
167 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
168 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
169 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
170 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
171 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
172 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
173 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
174 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
175 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
176 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
177
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100178static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700179 SHA_CTX ctx;
180 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100181 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700182 u_char digest[SHA_DIGEST_LENGTH];
183 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100185 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700186 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800188 }
189 return out;
190}
191
Prabir Pradhana3621852022-10-14 18:57:23 +0000192/* The set of all Android key codes that correspond to buttons (bit-switches) on a stylus. */
193static constexpr std::array<int32_t, 4> STYLUS_BUTTON_KEYCODES = {
194 AKEYCODE_STYLUS_BUTTON_PRIMARY,
195 AKEYCODE_STYLUS_BUTTON_SECONDARY,
196 AKEYCODE_STYLUS_BUTTON_TERTIARY,
197 AKEYCODE_STYLUS_BUTTON_TAIL,
198};
199
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800200/**
201 * Return true if name matches "v4l-touch*"
202 */
Chris Ye8594e192020-07-14 10:34:06 -0700203static bool isV4lTouchNode(std::string name) {
204 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800205}
206
Philip Quinn39b81682019-01-09 22:20:39 -0800207/**
208 * Returns true if V4L devices should be scanned.
209 *
210 * The system property ro.input.video_enabled can be used to control whether
211 * EventHub scans and opens V4L devices. As V4L does not support multiple
212 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700213 * them.
214 *
215 * Setting this to "false" would prevent any video devices from being discovered and
216 * associated with input devices.
217 *
218 * This property can be used as follows:
219 * 1. To turn off features that are dependent on video device presence.
220 * 2. During testing and development, to allow other clients to read video devices
221 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800222 */
223static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000224 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800225}
226
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800227static nsecs_t processEventTimestamp(const struct input_event& event) {
228 // Use the time specified in the event instead of the current time
229 // so that downstream code can get more accurate estimates of
230 // event dispatch latency from the time the event is enqueued onto
231 // the evdev client buffer.
232 //
233 // The event's timestamp fortuitously uses the same monotonic clock
234 // time base as the rest of Android. The kernel event device driver
235 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
236 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
237 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
238 // system call that also queries ktime_get_ts().
239
Colin Cross5b799302022-10-18 21:52:41 -0700240 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
241 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800242 return inputEventTime;
243}
244
Kim Low03ea0352020-11-06 12:45:07 -0800245/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000246 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800247 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800248static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800249 std::error_code errorCode;
250
251 // Stat the device path to get the major and minor number of the character file
252 struct stat statbuf;
253 if (stat(devicePath, &statbuf) == -1) {
254 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800255 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800256 }
257
258 unsigned int major_num = major(statbuf.st_rdev);
259 unsigned int minor_num = minor(statbuf.st_rdev);
260
261 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
262 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
263 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
264 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
265
266 // Make sure nothing went wrong in call to canonical()
267 if (errorCode) {
268 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
269 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800270 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800271 }
272
273 // Continue to go up a directory until we reach a directory named "input"
274 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
275 sysfsPath = sysfsPath.parent_path();
276 }
277
278 // Then go up one more and you will be at the sysfs root of the device
279 sysfsPath = sysfsPath.parent_path();
280
281 // Make sure we didn't reach root path and that directory actually exists
282 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
283 if (errorCode) {
284 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
285 errorCode.message().c_str());
286 }
287
288 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800289 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800290 }
291
292 return sysfsPath;
293}
294
295/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800296 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800297 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800298static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
299 std::vector<std::filesystem::path> nodes;
300 std::error_code errorCode;
301 auto iter = std::filesystem::directory_iterator(path, errorCode);
302 while (!errorCode && iter != std::filesystem::directory_iterator()) {
303 nodes.push_back(iter->path());
304 iter++;
305 }
306 return nodes;
307}
308
309/**
310 * Returns the list of files under a specified directory in a sysfs path.
311 * Example:
312 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
313 * in the sysfs path.
314 */
315static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
316 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800317 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800318 std::for_each(nodeStr.begin(), nodeStr.end(),
319 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
320 std::vector<std::filesystem::path> nodes;
321 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
322 nodes = allFilesInPath(path / nodeStr);
323 }
324 return nodes;
325}
326
327static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
328 std::filesystem::path path) {
329 std::string indexStr;
330 if (!base::ReadFileToString(path, &indexStr)) {
331 return std::nullopt;
332 }
333
334 // Parse the multi color LED index file, refer to kernel docs
335 // leds/leds-class-multicolor.html
336 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
337 std::smatch results;
338 std::array<LightColor, COLOR_NUM> colors;
339 if (!std::regex_match(indexStr, results, indexPattern)) {
340 return std::nullopt;
341 }
342
343 for (size_t i = 1; i < results.size(); i++) {
344 const auto it = LIGHT_COLORS.find(results[i].str());
345 if (it != LIGHT_COLORS.end()) {
346 // intensities.emplace(it->second, 0);
347 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800348 }
349 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800350 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800351}
352
Prabir Pradhancb42b472022-08-23 16:01:19 +0000353/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000354 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000355 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000356static std::optional<RawLayoutInfo> readLayoutConfiguration(
357 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000358 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000359 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000360 std::string str;
361 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
362 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000363 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000364 if (hidCountryCode > 35 || hidCountryCode < 0) {
365 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
366 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000367 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000368 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000369 const auto it = LAYOUT_INFOS.find(hidCountryCode);
370 if (it != LAYOUT_INFOS.end()) {
371 return it->second;
372 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000373
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000374 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000375}
376
377/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000378 * Read information about batteries exposed through the sysfs path.
379 */
380static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
381 const std::filesystem::path& sysfsRootPath) {
382 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
383 int32_t nextBatteryId = 0;
384 // Check if device has any battery.
385 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
386 for (const auto& nodePath : paths) {
387 RawBatteryInfo info;
388 info.id = ++nextBatteryId;
389 info.path = nodePath;
390 info.name = nodePath.filename();
391
392 // Scan the path for all the files
393 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
394 const auto& files = allFilesInPath(nodePath);
395 for (const auto& file : files) {
396 const auto it = BATTERY_CLASSES.find(file.filename().string());
397 if (it != BATTERY_CLASSES.end()) {
398 info.flags |= it->second;
399 }
400 }
401 batteryInfos.insert_or_assign(info.id, info);
402 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
403 }
404 return batteryInfos;
405}
406
407/**
408 * Read information about lights exposed through the sysfs path.
409 */
410static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
411 const std::filesystem::path& sysfsRootPath) {
412 std::unordered_map<int32_t, RawLightInfo> lightInfos;
413 int32_t nextLightId = 0;
414 // Check if device has any lights.
415 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
416 for (const auto& nodePath : paths) {
417 RawLightInfo info;
418 info.id = ++nextLightId;
419 info.path = nodePath;
420 info.name = nodePath.filename();
421 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000422
423 // Light name should follow the naming pattern <name>:<color>:<function>
424 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
425 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
426 std::smatch results;
427
428 if (std::regex_match(info.name, results, indexPattern)) {
429 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
430 // we only care about sections <color> and <function> which will be at index 2 and 3.
431 for (int i = 2; i <= 3; i++) {
432 const auto it = LIGHT_CLASSES.find(results.str(i));
433 if (it != LIGHT_CLASSES.end()) {
434 info.flags |= it->second;
435 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000436 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000437
438 // Set name of the raw light to <function> which represents playerIDs for LEDs that
439 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
440 // player ID logic)
441 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000442 }
443 // Scan the path for all the files
444 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
445 const auto& files = allFilesInPath(nodePath);
446 for (const auto& file : files) {
447 const auto it = LIGHT_CLASSES.find(file.filename().string());
448 if (it != LIGHT_CLASSES.end()) {
449 info.flags |= it->second;
450 // If the node has maximum brightness, read it
451 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
452 std::string str;
453 if (base::ReadFileToString(file, &str)) {
454 info.maxBrightness = std::stoi(str);
455 }
456 }
457 }
458 }
459 lightInfos.insert_or_assign(info.id, info);
460 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
461 }
462 return lightInfos;
463}
464
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465// --- Global Functions ---
466
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700467ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
468 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700470 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700472 case ABS_X:
473 case ABS_Y:
474 case ABS_PRESSURE:
475 case ABS_TOOL_WIDTH:
476 case ABS_DISTANCE:
477 case ABS_TILT_X:
478 case ABS_TILT_Y:
479 case ABS_MT_SLOT:
480 case ABS_MT_TOUCH_MAJOR:
481 case ABS_MT_TOUCH_MINOR:
482 case ABS_MT_WIDTH_MAJOR:
483 case ABS_MT_WIDTH_MINOR:
484 case ABS_MT_ORIENTATION:
485 case ABS_MT_POSITION_X:
486 case ABS_MT_POSITION_Y:
487 case ABS_MT_TOOL_TYPE:
488 case ABS_MT_BLOB_ID:
489 case ABS_MT_TRACKING_ID:
490 case ABS_MT_PRESSURE:
491 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700492 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 }
494 }
495
Chris Yef59a2f42020-10-16 12:55:26 -0700496 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
497 switch (axis) {
498 case ABS_X:
499 case ABS_Y:
500 case ABS_Z:
501 case ABS_RX:
502 case ABS_RY:
503 case ABS_RZ:
504 return InputDeviceClass::SENSOR;
505 }
506 }
507
Michael Wright842500e2015-03-13 17:32:02 -0700508 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700509 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700510 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700511 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700512 }
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700516 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517}
518
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000519// --- RawAbsoluteAxisInfo ---
520
521std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
522 if (info.valid) {
523 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
524 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
525 } else {
526 out << "unknown range";
527 }
528 return out;
529}
530
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531// --- EventHub::Device ---
532
Prabir Pradhancb42b472022-08-23 16:01:19 +0000533EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
534 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700535 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700536 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000537 path(std::move(path)),
538 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 classes(0),
540 configuration(nullptr),
541 virtualKeyMap(nullptr),
542 ffEffectPlaying(false),
543 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000544 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700545 controllerNumber(0),
546 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700547 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800548
549EventHub::Device::~Device() {
550 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551}
552
553void EventHub::Device::close() {
554 if (fd >= 0) {
555 ::close(fd);
556 fd = -1;
557 }
558}
559
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700560status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100561 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700562 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100563 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700564 return -errno;
565 }
566 enabled = true;
567 return OK;
568}
569
570status_t EventHub::Device::disable() {
571 close();
572 enabled = false;
573 return OK;
574}
575
Chris Ye989bb932020-07-04 16:18:59 -0700576bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700577 return !isVirtual && enabled;
578}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
Chris Ye3a1e4462020-08-12 10:13:15 -0700580const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700581 return keyMap.keyCharacterMap;
582}
583
584template <std::size_t N>
585status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
586 if (!hasValidFd()) {
587 return BAD_VALUE;
588 }
589 if ((_IOC_SIZE(ioctlCode) == 0)) {
590 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
591 }
592
593 typename BitArray<N>::Buffer buffer;
594 status_t ret = ioctl(fd, ioctlCode, buffer.data());
595 bitArray.loadFromBuffer(buffer);
596 return ret;
597}
598
599void EventHub::Device::configureFd() {
600 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
601 if (classes.test(InputDeviceClass::KEYBOARD)) {
602 // Disable kernel key repeat since we handle it ourselves
603 unsigned int repeatRate[] = {0, 0};
604 if (ioctl(fd, EVIOCSREP, repeatRate)) {
605 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
606 }
607 }
608
609 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
610 // associated with input events. This is important because the input system
611 // uses the timestamps extensively and assumes they were recorded using the monotonic
612 // clock.
613 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700614 if (classes.test(InputDeviceClass::SENSOR)) {
615 // Each new sensor event should use the same time base as
616 // SystemClock.elapsedRealtimeNanos().
617 clockId = CLOCK_BOOTTIME;
618 }
Chris Ye989bb932020-07-04 16:18:59 -0700619 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
620 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
621}
622
623bool EventHub::Device::hasKeycodeLocked(int keycode) const {
624 if (!keyMap.haveKeyLayout()) {
625 return false;
626 }
627
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700628 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700629 const size_t N = scanCodes.size();
630 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
631 int32_t sc = scanCodes[i];
632 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
633 return true;
634 }
635 }
636
Charles Linaadf8d52023-03-30 13:34:54 +0800637 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
638 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
639 return true;
640 }
641
Chris Ye989bb932020-07-04 16:18:59 -0700642 return false;
643}
644
645void EventHub::Device::loadConfigurationLocked() {
646 configurationFile =
647 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
648 InputDeviceConfigurationFileType::
649 CONFIGURATION);
650 if (configurationFile.empty()) {
651 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
652 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500653 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
654 PropertyMap::load(configurationFile.c_str());
655 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700656 ALOGE("Error loading input device configuration file for device '%s'. "
657 "Using default configuration.",
658 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500659 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500660 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700661 }
662 }
663}
664
665bool EventHub::Device::loadVirtualKeyMapLocked() {
666 // The virtual key map is supplied by the kernel as a system board property file.
667 std::string propPath = "/sys/board_properties/virtualkeys.";
668 propPath += identifier.getCanonicalName();
669 if (access(propPath.c_str(), R_OK)) {
670 return false;
671 }
672 virtualKeyMap = VirtualKeyMap::load(propPath);
673 return virtualKeyMap != nullptr;
674}
675
676status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500677 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700678}
679
680bool EventHub::Device::isExternalDeviceLocked() {
681 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000682 std::optional<bool> isInternal = configuration->getBool("device.internal");
683 if (isInternal.has_value()) {
684 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700685 }
686 }
687 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
688}
689
690bool EventHub::Device::deviceHasMicLocked() {
691 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000692 std::optional<bool> hasMic = configuration->getBool("audio.mic");
693 if (hasMic.has_value()) {
694 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700695 }
696 }
697 return false;
698}
699
700void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
701 int32_t sc;
702 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
703 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700704 ev.input_event_sec = 0;
705 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700706 ev.type = EV_LED;
707 ev.code = sc;
708 ev.value = on ? 1 : 0;
709
710 ssize_t nWrite;
711 do {
712 nWrite = write(fd, &ev, sizeof(struct input_event));
713 } while (nWrite == -1 && errno == EINTR);
714 }
715}
716
717void EventHub::Device::setLedForControllerLocked() {
718 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
719 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
720 }
721}
722
723status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
724 if (!keyMap.haveKeyLayout()) {
725 return NAME_NOT_FOUND;
726 }
727
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700728 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
729 if (scanCode.has_value()) {
730 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
731 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700732 return NO_ERROR;
733 }
734 }
735 return NAME_NOT_FOUND;
736}
737
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100738/**
739 * Get the capabilities for the current process.
740 * Crashes the system if unable to create / check / destroy the capabilities object.
741 */
742class Capabilities final {
743public:
744 explicit Capabilities() {
745 mCaps = cap_get_proc();
746 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
747 }
748
749 /**
750 * Check whether the current process has a specific capability
751 * in the set of effective capabilities.
752 * Return CAP_SET if the process has the requested capability
753 * Return CAP_CLEAR otherwise.
754 */
755 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
756 cap_flag_value_t value;
757 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
758 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
759 return value;
760 }
761
762 ~Capabilities() {
763 const int result = cap_free(mCaps);
764 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
765 }
766
767private:
768 cap_t mCaps;
769};
770
771static void ensureProcessCanBlockSuspend() {
772 Capabilities capabilities;
773 const bool canBlockSuspend =
774 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
775 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
776 "Input must be able to block suspend to properly process events");
777}
778
Michael Wrightd02c5b62014-02-10 15:10:22 -0800779// --- EventHub ---
780
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781const int EventHub::EPOLL_MAX_EVENTS;
782
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700783EventHub::EventHub(void)
784 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
785 mNextDeviceId(1),
786 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800787 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700788 mNeedToReopenDevices(false),
789 mNeedToScanDevices(true),
790 mPendingEventCount(0),
791 mPendingEventIndex(0),
792 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100793 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800794
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800795 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800796 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800797
Michael Wright8e9a8562022-02-09 13:44:29 +0000798 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000799 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100800
801 std::error_code errorCode;
802 bool isDeviceInotifyAdded = false;
803 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
804 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800805 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100806 addDeviceInotify();
807 isDeviceInotifyAdded = true;
808 if (errorCode) {
809 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
810 errorCode.message().c_str());
811 }
812 }
813
814 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
815 addDeviceInotify();
816 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800817 ALOGI("Video device scanning disabled");
818 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100820 struct epoll_event eventItem = {};
821 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700822 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800823 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
825
826 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000827 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800828 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
829
830 mWakeReadPipeFd = wakeFds[0];
831 mWakeWritePipeFd = wakeFds[1];
832
833 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
834 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700835 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836
837 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
838 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700839 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700841 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
843 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700844 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845}
846
847EventHub::~EventHub(void) {
848 closeAllDevicesLocked();
849
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 ::close(mEpollFd);
851 ::close(mINotifyFd);
852 ::close(mWakeReadPipeFd);
853 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854}
855
Usama Arifb27c8e62021-06-03 16:44:09 +0100856/**
857 * On devices that don't have any input devices (like some development boards), the /dev/input
858 * directory will be absent. However, the user may still plug in an input device at a later time.
859 * Add watch for contents of /dev/input only when /dev/input appears.
860 */
861void EventHub::addDeviceInputInotify() {
862 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
863 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
864 DEVICE_INPUT_PATH, strerror(errno));
865}
866
867void EventHub::addDeviceInotify() {
868 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
869 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
870 strerror(errno));
871}
872
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000874 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700876 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700879ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000880 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700882 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883}
884
885int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000886 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700888 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889}
890
Harry Cuttsc34f7582023-03-07 16:23:30 +0000891std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000892 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000894 if (device == nullptr || device->configuration == nullptr) {
895 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000897 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898}
899
900status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700901 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 outAxisInfo->clear();
903
904 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000905 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906
907 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700908 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800909 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700910 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
911 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
912 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913 return -errno;
914 }
915
916 if (info.minimum != info.maximum) {
917 outAxisInfo->valid = true;
918 outAxisInfo->minValue = info.minimum;
919 outAxisInfo->maxValue = info.maximum;
920 outAxisInfo->flat = info.flat;
921 outAxisInfo->fuzz = info.fuzz;
922 outAxisInfo->resolution = info.resolution;
923 }
924 return OK;
925 }
926 }
927 return -1;
928}
929
930bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
931 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000932 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700934 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935 }
936 return false;
937}
938
939bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000940 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941
Chris Ye989bb932020-07-04 16:18:59 -0700942 Device* device = getDeviceLocked(deviceId);
943 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
944 ? device->propBitmask.test(property)
945 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800946}
947
Chris Yef59a2f42020-10-16 12:55:26 -0700948bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
949 std::scoped_lock _l(mLock);
950
951 Device* device = getDeviceLocked(deviceId);
952 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
953 ? device->mscBitmask.test(mscEvent)
954 : false;
955}
956
Michael Wrightd02c5b62014-02-10 15:10:22 -0800957int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
958 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000959 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960
961 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700962 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
963 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
964 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965 }
966 }
967 }
968 return AKEY_STATE_UNKNOWN;
969}
970
971int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000972 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800973
974 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700975 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700976 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700978 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800980 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700981 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982 return AKEY_STATE_DOWN;
983 }
984 }
985 return AKEY_STATE_UP;
986 }
987 }
988 }
989 return AKEY_STATE_UNKNOWN;
990}
991
Philip Junker4af3b3d2021-12-14 10:36:55 +0100992int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
993 std::scoped_lock _l(mLock);
994
995 Device* device = getDeviceLocked(deviceId);
996 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
997 device->keyMap.keyLayoutMap == nullptr) {
998 return AKEYCODE_UNKNOWN;
999 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001000 std::vector<int32_t> scanCodes =
1001 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001002 if (scanCodes.empty()) {
1003 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1004 "device %d",
1005 locationKeyCode, deviceId);
1006 return AKEYCODE_UNKNOWN;
1007 }
1008 if (scanCodes.size() > 1) {
1009 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1010 locationKeyCode);
1011 }
1012 int32_t outKeyCode;
1013 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001014 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001015 switch (mapKeyRes) {
1016 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001017 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001018 case NAME_NOT_FOUND:
1019 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001020 outKeyCode = locationKeyCode;
1021 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001022 default:
1023 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1024 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001025 outKeyCode = AKEYCODE_UNKNOWN;
1026 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001027 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001028 // Remap if there is a Key remapping added to the KCM and return the remapped key
1029 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001030}
1031
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1033 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001034 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035
1036 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001037 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
1038 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
1039 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 }
1041 }
1042 }
1043 return AKEY_STATE_UNKNOWN;
1044}
1045
1046status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1047 *outValue = 0;
1048
1049 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001050 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051
1052 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001053 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001054 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001055 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
1056 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
1057 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 return -errno;
1059 }
1060
1061 *outValue = info.value;
1062 return OK;
1063 }
1064 }
1065 return -1;
1066}
1067
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001068bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001069 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001070 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071
1072 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001073 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001074 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001075 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1076 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001077 }
1078 }
1079 return true;
1080 }
1081 return false;
1082}
1083
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001084void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1085 std::scoped_lock _l(mLock);
1086 Device* device = getDeviceLocked(deviceId);
1087 if (device == nullptr) {
1088 return;
1089 }
1090 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1091 if (kcm) {
1092 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1093 }
1094}
1095
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001096status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1097 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001098 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001099 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001100 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001101
Chris Ye66fbac32020-07-06 20:36:43 -07001102 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001103 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001104 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1105 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1107 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001108 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 }
1110 }
1111
1112 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001113 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001114 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001115 status = NO_ERROR;
1116 }
1117 }
1118
1119 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001120 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001121 // Remap keys based on user-defined key remappings and key behavior defined in the
1122 // corresponding kcm file
1123 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1124
1125 // Remap keys based on Key behavior defined in KCM file
1126 std::tie(*outKeycode, *outMetaState) =
1127 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001128 } else {
1129 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
1131 }
1132 }
1133
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001134 if (status != NO_ERROR) {
1135 *outKeycode = 0;
1136 *outFlags = 0;
1137 *outMetaState = metaState;
1138 }
1139
1140 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141}
1142
1143status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001144 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145 Device* device = getDeviceLocked(deviceId);
1146
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001147 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1148 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001149 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001150 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1151 if (!info.has_value()) {
1152 return NAME_NOT_FOUND;
1153 }
1154 *outAxisInfo = *info;
1155 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156}
1157
Chris Yef59a2f42020-10-16 12:55:26 -07001158base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001159 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001160 std::scoped_lock _l(mLock);
1161 Device* device = getDeviceLocked(deviceId);
1162
1163 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1164 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1165 }
1166 return Errorf("Device not found or device has no key layout.");
1167}
1168
Chris Yee2b1e5c2021-03-10 22:45:12 -08001169// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1170// associated with the device ID. Returns an empty map if no miscellaneous device found.
1171const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1172 int32_t deviceId) const {
1173 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1174 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001175 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001176 return EMPTY_BATTERY_INFO;
1177 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001178 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001179}
1180
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001181std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001182 std::scoped_lock _l(mLock);
1183 std::vector<int32_t> batteryIds;
1184
Prabir Pradhan51894782022-08-23 16:29:10 +00001185 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001186 batteryIds.push_back(id);
1187 }
1188
1189 return batteryIds;
1190}
1191
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001192std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1193 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001194 std::scoped_lock _l(mLock);
1195
1196 const auto infos = getBatteryInfoLocked(deviceId);
1197
1198 auto it = infos.find(batteryId);
1199 if (it != infos.end()) {
1200 return it->second;
1201 }
1202
1203 return std::nullopt;
1204}
1205
1206// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001207// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001208const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1209 int32_t deviceId) const {
1210 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1211 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001212 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001213 return EMPTY_LIGHT_INFO;
1214 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001215 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001216}
1217
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001218std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001219 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001220 std::vector<int32_t> lightIds;
1221
Prabir Pradhan51894782022-08-23 16:29:10 +00001222 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001223 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001224 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001225
Chris Ye3fdbfef2021-01-06 18:45:18 -08001226 return lightIds;
1227}
1228
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001229std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001230 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001231
Chris Yee2b1e5c2021-03-10 22:45:12 -08001232 const auto infos = getLightInfoLocked(deviceId);
1233
1234 auto it = infos.find(lightId);
1235 if (it != infos.end()) {
1236 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001237 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001238
Chris Ye3fdbfef2021-01-06 18:45:18 -08001239 return std::nullopt;
1240}
1241
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001242std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001243 std::scoped_lock _l(mLock);
1244
Chris Yee2b1e5c2021-03-10 22:45:12 -08001245 const auto infos = getLightInfoLocked(deviceId);
1246 auto it = infos.find(lightId);
1247 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001248 return std::nullopt;
1249 }
1250 std::string buffer;
1251 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1252 &buffer)) {
1253 return std::nullopt;
1254 }
1255 return std::stoi(buffer);
1256}
1257
1258std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001259 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001260 std::scoped_lock _l(mLock);
1261
Chris Yee2b1e5c2021-03-10 22:45:12 -08001262 const auto infos = getLightInfoLocked(deviceId);
1263 auto lightIt = infos.find(lightId);
1264 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001265 return std::nullopt;
1266 }
1267
1268 auto ret =
1269 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1270
1271 if (!ret.has_value()) {
1272 return std::nullopt;
1273 }
1274 std::array<LightColor, COLOR_NUM> colors = ret.value();
1275
1276 std::string intensityStr;
1277 if (!base::ReadFileToString(lightIt->second.path /
1278 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1279 &intensityStr)) {
1280 return std::nullopt;
1281 }
1282
1283 // Intensity node outputs 3 color values
1284 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1285 std::smatch results;
1286
1287 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1288 return std::nullopt;
1289 }
1290 std::unordered_map<LightColor, int32_t> intensities;
1291 for (size_t i = 1; i < results.size(); i++) {
1292 int value = std::stoi(results[i].str());
1293 intensities.emplace(colors[i - 1], value);
1294 }
1295 return intensities;
1296}
1297
1298void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1299 std::scoped_lock _l(mLock);
1300
Chris Yee2b1e5c2021-03-10 22:45:12 -08001301 const auto infos = getLightInfoLocked(deviceId);
1302 auto lightIt = infos.find(lightId);
1303 if (lightIt == infos.end()) {
1304 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001305 return;
1306 }
1307
1308 if (!base::WriteStringToFile(std::to_string(brightness),
1309 lightIt->second.path /
1310 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1311 ALOGE("Can not write to file, error: %s", strerror(errno));
1312 }
1313}
1314
1315void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1316 std::unordered_map<LightColor, int32_t> intensities) {
1317 std::scoped_lock _l(mLock);
1318
Chris Yee2b1e5c2021-03-10 22:45:12 -08001319 const auto infos = getLightInfoLocked(deviceId);
1320 auto lightIt = infos.find(lightId);
1321 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001322 ALOGE("Light Id %d does not exist.", lightId);
1323 return;
1324 }
1325
1326 auto ret =
1327 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1328
1329 if (!ret.has_value()) {
1330 return;
1331 }
1332 std::array<LightColor, COLOR_NUM> colors = ret.value();
1333
1334 std::string rgbStr;
1335 for (size_t i = 0; i < COLOR_NUM; i++) {
1336 auto it = intensities.find(colors[i]);
1337 if (it != intensities.end()) {
1338 rgbStr += std::to_string(it->second);
1339 // Insert space between colors
1340 if (i < COLOR_NUM - 1) {
1341 rgbStr += " ";
1342 }
1343 }
1344 }
1345 // Append new line
1346 rgbStr += "\n";
1347
1348 if (!base::WriteStringToFile(rgbStr,
1349 lightIt->second.path /
1350 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1351 ALOGE("Can not write to file, error: %s", strerror(errno));
1352 }
1353}
1354
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001355std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001356 std::scoped_lock _l(mLock);
1357 Device* device = getDeviceLocked(deviceId);
1358 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001359 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001360 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001361 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001362}
1363
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001364void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001365 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001366
1367 mExcludedDevices = devices;
1368}
1369
1370bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001371 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001372 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001373 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1374 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 }
1376 return false;
1377}
1378
Arthur Hungcb40a002021-08-03 14:31:01 +00001379bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1380 std::scoped_lock _l(mLock);
1381 Device* device = getDeviceLocked(deviceId);
1382 if (device != nullptr) {
1383 return device->hasKeycodeLocked(keyCode);
1384 }
1385 return false;
1386}
1387
Michael Wrightd02c5b62014-02-10 15:10:22 -08001388bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001389 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001390 Device* device = getDeviceLocked(deviceId);
1391 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001392 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001393 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001394 }
1395 return false;
1396}
1397
1398void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001399 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001400 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001401 if (device != nullptr && device->hasValidFd()) {
1402 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 }
1404}
1405
1406void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001407 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001408 outVirtualKeys.clear();
1409
Chris Ye87143712020-11-10 05:05:58 +00001410 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001412 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001413 const std::vector<VirtualKeyDefinition> virtualKeys =
1414 device->virtualKeyMap->getVirtualKeys();
1415 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001416 }
1417}
1418
Chris Ye3a1e4462020-08-12 10:13:15 -07001419const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001420 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001421 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001422 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001423 return device->getKeyCharacterMap();
1424 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001425 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426}
1427
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001428// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001429bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001430 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001431 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001432 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001433 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001435 if (map == nullptr) {
1436 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1437 return true;
1438 }
Philip Junker90bc9492021-12-10 18:39:42 +01001439 device->keyMap.keyCharacterMap->combine(*map);
1440 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001441}
1442
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001443static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1444 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001445 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001446 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001447 if (!identifier.uniqueId.empty()) {
1448 rawDescriptor += "uniqueId:";
1449 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001450 }
1451 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001452 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 }
1454
1455 if (identifier.vendor == 0 && identifier.product == 0) {
1456 // If we don't know the vendor and product id, then the device is probably
1457 // built-in so we need to rely on other information to uniquely identify
1458 // the input device. Usually we try to avoid relying on the device name or
1459 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001460 if (!identifier.name.empty()) {
1461 rawDescriptor += "name:";
1462 rawDescriptor += identifier.name;
1463 } else if (!identifier.location.empty()) {
1464 rawDescriptor += "location:";
1465 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001466 }
1467 }
1468 identifier.descriptor = sha1(rawDescriptor);
1469 return rawDescriptor;
1470}
1471
1472void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1473 // Compute a device descriptor that uniquely identifies the device.
1474 // The descriptor is assumed to be a stable identifier. Its value should not
1475 // change between reboots, reconnections, firmware updates or new releases
1476 // of Android. In practice we sometimes get devices that cannot be uniquely
1477 // identified. In this case we enforce uniqueness between connected devices.
1478 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001479 // Note that we explicitly do not use the path or location for external devices
1480 // as their path or location will change as they are plugged/unplugged or moved
1481 // to different ports. We do fallback to using name and location in the case of
1482 // internal devices which are detected by the vendor and product being 0 in
1483 // generateDescriptor. If two identical descriptors are detected we will fallback
1484 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1485 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486
1487 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001488 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001489 // Enforce that the generated descriptor is unique.
1490 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1491 identifier.nonce++;
1492 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001494 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001495 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496}
1497
Prabir Pradhancb42b472022-08-23 16:01:19 +00001498std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1499 const std::filesystem::path& devicePath) const {
1500 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1501 getSysfsRootPath(devicePath.c_str());
1502 if (!sysfsRootPathOpt) {
1503 return nullptr;
1504 }
1505
1506 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001507
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001508 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001509 AssociatedDevice{.sysfsRootPath = path,
1510 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001511 .lightInfos = readLightsConfiguration(path),
1512 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001513
1514 bool associatedDeviceChanged = false;
1515 for (const auto& [id, dev] : mDevices) {
1516 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1517 if (*associatedDevice != *dev->associatedDevice) {
1518 associatedDeviceChanged = true;
1519 dev->associatedDevice = associatedDevice;
1520 }
1521 associatedDevice = dev->associatedDevice;
1522 }
1523 }
1524 ALOGI_IF(associatedDeviceChanged,
1525 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1526 path.c_str(), associatedDevice->dump().c_str());
1527
1528 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001529}
1530
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001531bool EventHub::AssociatedDevice::isChanged() const {
1532 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1533 readBatteryConfiguration(sysfsRootPath);
1534 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1535 readLightsConfiguration(sysfsRootPath);
1536 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1537
1538 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1539 newLayoutInfo == layoutInfo) {
1540 return false;
1541 }
1542 return true;
1543}
1544
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001545void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001546 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001548 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 ff_effect effect;
1550 memset(&effect, 0, sizeof(effect));
1551 effect.type = FF_RUMBLE;
1552 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001553 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001554 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1555 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001556 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 effect.replay.delay = 0;
1558 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1559 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001560 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001561 return;
1562 }
1563 device->ffEffectId = effect.id;
1564
1565 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001566 ev.input_event_sec = 0;
1567 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001568 ev.type = EV_FF;
1569 ev.code = device->ffEffectId;
1570 ev.value = 1;
1571 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1572 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001573 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001574 return;
1575 }
1576 device->ffEffectPlaying = true;
1577 }
1578}
1579
1580void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001581 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001582 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001583 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 if (device->ffEffectPlaying) {
1585 device->ffEffectPlaying = false;
1586
1587 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001588 ev.input_event_sec = 0;
1589 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001590 ev.type = EV_FF;
1591 ev.code = device->ffEffectId;
1592 ev.value = 0;
1593 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1594 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001595 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001596 return;
1597 }
1598 }
1599 }
1600}
1601
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001602std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001603 std::scoped_lock _l(mLock);
1604 std::vector<int32_t> vibrators;
1605 Device* device = getDeviceLocked(deviceId);
1606 if (device != nullptr && device->hasValidFd() &&
1607 device->classes.test(InputDeviceClass::VIBRATOR)) {
1608 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1609 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1610 }
1611 return vibrators;
1612}
1613
Josh Bartel938632f2022-07-19 15:34:22 -05001614/**
1615 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1616 */
1617bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1618 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001619 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001620 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001621 }
1622 }
Josh Bartel938632f2022-07-19 15:34:22 -05001623
1624 for (const auto& [id, device] : mDevices) {
1625 if (descriptor == device->identifier.descriptor) {
1626 return true;
1627 }
1628 }
1629 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001630}
1631
1632EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001633 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001634 deviceId = mBuiltInKeyboardId;
1635 }
Chris Ye989bb932020-07-04 16:18:59 -07001636 const auto& it = mDevices.find(deviceId);
1637 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001638}
1639
Chris Ye8594e192020-07-14 10:34:06 -07001640EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001641 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001642 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001643 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644 }
1645 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001646 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001647}
1648
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001649/**
1650 * The file descriptor could be either input device, or a video device (associated with a
1651 * specific input device). Check both cases here, and return the device that this event
1652 * belongs to. Caller can compare the fd's once more to determine event type.
1653 * Looks through all input devices, and only attached video devices. Unattached video
1654 * devices are ignored.
1655 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001656EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001657 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001658 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001659 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001660 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001661 }
1662 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1663 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001664 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001665 }
1666 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001667 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1668 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001669 return nullptr;
1670}
1671
Chris Yee2b1e5c2021-03-10 22:45:12 -08001672std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001673 std::filesystem::path batteryPath;
1674 {
1675 // Do not read the sysfs node to get the battery state while holding
1676 // the EventHub lock. For some peripheral devices, reading battery state
1677 // can be broken and take 5+ seconds. Holding the lock in this case would
1678 // block all other event processing during this time. For now, we assume this
1679 // call never happens on the InputReader thread and read the sysfs node outside
1680 // the lock to prevent event processing from being blocked by this call.
1681 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001682
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001683 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001684 auto it = infos.find(batteryId);
1685 if (it == infos.end()) {
1686 return std::nullopt;
1687 }
1688 batteryPath = it->second.path;
1689 } // release lock
1690
Chris Yee2b1e5c2021-03-10 22:45:12 -08001691 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001692
1693 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001694 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001695 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001696 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001697 }
1698
1699 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1700 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001701 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001702 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001703 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001704 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1705 if (levelIt != BATTERY_LEVEL.end()) {
1706 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001707 }
1708 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001709
Kim Low03ea0352020-11-06 12:45:07 -08001710 return std::nullopt;
1711}
1712
Chris Yee2b1e5c2021-03-10 22:45:12 -08001713std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001714 std::filesystem::path batteryPath;
1715 {
1716 // Do not read the sysfs node to get the battery state while holding
1717 // the EventHub lock. For some peripheral devices, reading battery state
1718 // can be broken and take 5+ seconds. Holding the lock in this case would
1719 // block all other event processing during this time. For now, we assume this
1720 // call never happens on the InputReader thread and read the sysfs node outside
1721 // the lock to prevent event processing from being blocked by this call.
1722 std::scoped_lock _l(mLock);
1723
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001724 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001725 auto it = infos.find(batteryId);
1726 if (it == infos.end()) {
1727 return std::nullopt;
1728 }
1729 batteryPath = it->second.path;
1730 } // release lock
1731
Chris Yee2b1e5c2021-03-10 22:45:12 -08001732 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001733
Andy Chenf9f1a022022-08-29 20:07:10 -04001734 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001735 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001736 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1737 return std::nullopt;
1738 }
1739
Chris Yed1936772021-02-22 10:30:40 -08001740 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001741 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1742 if (statusIt != BATTERY_STATUS.end()) {
1743 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001744 }
1745
1746 return std::nullopt;
1747}
1748
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001749std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001750 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001751
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001752 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001753
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001754 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001755 bool awoken = false;
1756 for (;;) {
1757 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1758
1759 // Reopen input devices if needed.
1760 if (mNeedToReopenDevices) {
1761 mNeedToReopenDevices = false;
1762
1763 ALOGI("Reopening all input devices due to a configuration change.");
1764
1765 closeAllDevicesLocked();
1766 mNeedToScanDevices = true;
1767 break; // return to the caller before we actually rescan
1768 }
1769
1770 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001771 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1772 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001773 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001774 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001775 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1776 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001777 events.push_back({
1778 .when = now,
1779 .deviceId = deviceId,
1780 .type = DEVICE_REMOVED,
1781 });
Chris Ye989bb932020-07-04 16:18:59 -07001782 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001783 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001784 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001785 break;
1786 }
1787 }
1788
1789 if (mNeedToScanDevices) {
1790 mNeedToScanDevices = false;
1791 scanDevicesLocked();
1792 mNeedToSendFinishedDeviceScan = true;
1793 }
1794
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001795 while (!mOpeningDevices.empty()) {
1796 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1797 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001798 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001799 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1800 events.push_back({
1801 .when = now,
1802 .deviceId = deviceId,
1803 .type = DEVICE_ADDED,
1804 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001805
1806 // Try to find a matching video device by comparing device names
1807 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1808 it++) {
1809 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001810 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001811 // videoDevice was transferred to 'device'
1812 it = mUnattachedVideoDevices.erase(it);
1813 break;
1814 }
1815 }
1816
1817 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1818 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001819 ALOGW("Device id %d exists, replaced.", device->id);
1820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001821 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001822 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 break;
1824 }
1825 }
1826
1827 if (mNeedToSendFinishedDeviceScan) {
1828 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001829 events.push_back({
1830 .when = now,
1831 .type = FINISHED_DEVICE_SCAN,
1832 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001833 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001834 break;
1835 }
1836 }
1837
1838 // Grab the next input event.
1839 bool deviceChanged = false;
1840 while (mPendingEventIndex < mPendingEventCount) {
1841 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001842 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843 if (eventItem.events & EPOLLIN) {
1844 mPendingINotify = true;
1845 } else {
1846 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1847 }
1848 continue;
1849 }
1850
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001851 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 if (eventItem.events & EPOLLIN) {
1853 ALOGV("awoken after wake()");
1854 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001855 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001856 ssize_t nRead;
1857 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001858 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1859 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 } else {
1861 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001862 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001863 }
1864 continue;
1865 }
1866
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001867 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001868 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001869 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1870 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001871 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001872 continue;
1873 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001874 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1875 if (eventItem.events & EPOLLIN) {
1876 size_t numFrames = device->videoDevice->readAndQueueFrames();
1877 if (numFrames == 0) {
1878 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001879 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001880 }
1881 } else if (eventItem.events & EPOLLHUP) {
1882 // TODO(b/121395353) - consider adding EPOLLRDHUP
1883 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001884 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001885 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1886 device->videoDevice = nullptr;
1887 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001888 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1889 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001890 ALOG_ASSERT(!DEBUG);
1891 }
1892 continue;
1893 }
1894 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001896 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001897 read(device->fd, readBuffer.data(),
1898 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001899 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1900 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001901 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001902 " capacity: %zu errno: %d)\n",
1903 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001904 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001905 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001906 } else if (readSize < 0) {
1907 if (errno != EAGAIN && errno != EINTR) {
1908 ALOGW("could not get event (errno=%d)", errno);
1909 }
1910 } else if ((readSize % sizeof(struct input_event)) != 0) {
1911 ALOGE("could not get event (wrong size: %d)", readSize);
1912 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001913 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001914
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001915 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001916 for (size_t i = 0; i < count; i++) {
1917 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001918 events.push_back({
1919 .when = processEventTimestamp(iev),
1920 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1921 .deviceId = deviceId,
1922 .type = iev.type,
1923 .code = iev.code,
1924 .value = iev.value,
1925 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001927 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 // The result buffer is full. Reset the pending event index
1929 // so we will try to read the device again on the next iteration.
1930 mPendingEventIndex -= 1;
1931 break;
1932 }
1933 }
1934 } else if (eventItem.events & EPOLLHUP) {
1935 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001936 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001938 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001940 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1941 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942 }
1943 }
1944
1945 // readNotify() will modify the list of devices so this must be done after
1946 // processing all other events to ensure that we read all remaining events
1947 // before closing the devices.
1948 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1949 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001950 const auto res = readNotifyLocked();
1951 if (!res.ok()) {
1952 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1953 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954 deviceChanged = true;
1955 }
1956
1957 // Report added or removed devices immediately.
1958 if (deviceChanged) {
1959 continue;
1960 }
1961
1962 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001963 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 break;
1965 }
1966
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001967 // Poll for events.
1968 // When a device driver has pending (unread) events, it acquires
1969 // a kernel wake lock. Once the last pending event has been read, the device
1970 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1971 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1972 // is called again for the same fd that produced the event.
1973 // Thus the system can only sleep if there are no events pending or
1974 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975 //
1976 // The timeout is advisory only. If the device is asleep, it will not wake just to
1977 // service the timeout.
1978 mPendingEventIndex = 0;
1979
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001980 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001981
1982 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1983
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001984 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985
1986 if (pollResult == 0) {
1987 // Timed out.
1988 mPendingEventCount = 0;
1989 break;
1990 }
1991
1992 if (pollResult < 0) {
1993 // An error occurred.
1994 mPendingEventCount = 0;
1995
1996 // Sleep after errors to avoid locking up the system.
1997 // Hopefully the error is transient.
1998 if (errno != EINTR) {
1999 ALOGW("poll failed (errno=%d)\n", errno);
2000 usleep(100000);
2001 }
2002 } else {
2003 // Some events occurred.
2004 mPendingEventCount = size_t(pollResult);
2005 }
2006 }
2007
2008 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002009 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002010}
2011
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002012std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002013 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002014
2015 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002016 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002017 return {};
2018 }
2019 return device->videoDevice->consumeFrames();
2020}
2021
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022void EventHub::wake() {
2023 ALOGV("wake() called");
2024
2025 ssize_t nWrite;
2026 do {
2027 nWrite = write(mWakeWritePipeFd, "W", 1);
2028 } while (nWrite == -1 && errno == EINTR);
2029
2030 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002031 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 }
2033}
2034
2035void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002036 status_t result;
2037 std::error_code errorCode;
2038
2039 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2040 result = scanDirLocked(DEVICE_INPUT_PATH);
2041 if (result < 0) {
2042 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2043 }
2044 } else {
2045 if (errorCode) {
2046 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2047 errorCode.message().c_str());
2048 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002049 }
Philip Quinn39b81682019-01-09 22:20:39 -08002050 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002051 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002052 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002053 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002054 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002055 }
Chris Ye989bb932020-07-04 16:18:59 -07002056 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 createVirtualKeyboardLocked();
2058 }
2059}
2060
2061// ----------------------------------------------------------------------------
2062
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002064 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
2065 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
2066 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
2067 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
2068 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
2069 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08002070};
2071
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002072status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002073 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002074 struct epoll_event eventItem = {};
2075 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2076 eventItem.data.fd = fd;
2077 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2078 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002079 return -errno;
2080 }
2081 return OK;
2082}
2083
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002084status_t EventHub::unregisterFdFromEpoll(int fd) {
2085 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2086 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2087 return -errno;
2088 }
2089 return OK;
2090}
2091
Chris Ye989bb932020-07-04 16:18:59 -07002092status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2093 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002094 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002095 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002096 return result;
2097 }
Chris Ye989bb932020-07-04 16:18:59 -07002098 if (device.videoDevice) {
2099 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002100 }
2101 return result;
2102}
2103
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002104void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2105 status_t result = registerFdForEpoll(videoDevice.getFd());
2106 if (result != OK) {
2107 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2108 }
2109}
2110
Chris Ye989bb932020-07-04 16:18:59 -07002111status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2112 if (device.hasValidFd()) {
2113 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002114 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002115 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002116 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002117 }
2118 }
Chris Ye989bb932020-07-04 16:18:59 -07002119 if (device.videoDevice) {
2120 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002121 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002122 return OK;
2123}
2124
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002125void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2126 if (videoDevice.hasValidFd()) {
2127 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2128 if (result != OK) {
2129 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002130 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002131 }
2132 }
2133}
2134
Chris Yed3fef462021-03-07 17:10:08 -08002135void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002136 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002137 SHA256_CTX ctx;
2138 SHA256_Init(&ctx);
2139 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2140 identifier.uniqueId.size());
2141 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2142 SHA256_Final(digest.data(), &ctx);
2143
2144 std::string obfuscatedId;
2145 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2146 obfuscatedId += StringPrintf("%02x", digest[i]);
2147 }
2148
Chris Yed3fef462021-03-07 17:10:08 -08002149 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2150 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002151 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002152}
2153
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002154void EventHub::openDeviceLocked(const std::string& devicePath) {
2155 // If an input device happens to register around the time when EventHub's constructor runs, it
2156 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2157 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2158 // from getting registered, ensure that this path is not already covered by an existing device.
2159 for (const auto& [deviceId, device] : mDevices) {
2160 if (device->path == devicePath) {
2161 return; // device was already registered
2162 }
2163 }
2164
Michael Wrightd02c5b62014-02-10 15:10:22 -08002165 char buffer[80];
2166
Chris Ye8594e192020-07-14 10:34:06 -07002167 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168
Chris Ye8594e192020-07-14 10:34:06 -07002169 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002170 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002171 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002172 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002173 }
2174
2175 InputDeviceIdentifier identifier;
2176
2177 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002178 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002179 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002180 } else {
2181 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002182 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183 }
2184
2185 // Check to see if the device is on our excluded list
2186 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002187 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002189 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002191 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192 }
2193 }
2194
2195 // Get device driver version.
2196 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002197 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002198 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002199 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002200 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201 }
2202
2203 // Get device identifier.
2204 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002205 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002206 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002208 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002209 }
2210 identifier.bus = inputId.bustype;
2211 identifier.product = inputId.product;
2212 identifier.vendor = inputId.vendor;
2213 identifier.version = inputId.version;
2214
2215 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002216 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2217 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 } else {
2219 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002220 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002221 }
2222
2223 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002224 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2225 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002226 } else {
2227 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002228 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 }
2230
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002231 // Attempt to get the bluetooth address of an input device from the uniqueId.
2232 if (identifier.bus == BUS_BLUETOOTH &&
2233 std::regex_match(identifier.uniqueId,
2234 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2235 identifier.bluetoothAddress = identifier.uniqueId;
2236 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2237 for (auto& c : *identifier.bluetoothAddress) {
2238 c = ::toupper(c);
2239 }
2240 }
2241
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 // Fill in the descriptor.
2243 assignDescriptorLocked(identifier);
2244
Michael Wrightd02c5b62014-02-10 15:10:22 -08002245 // Allocate device. (The device object takes ownership of the fd at this point.)
2246 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002247 std::unique_ptr<Device> device =
2248 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2249 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250
Chris Ye8594e192020-07-14 10:34:06 -07002251 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002253 " vendor %04x\n"
2254 " product %04x\n"
2255 " version %04x\n",
2256 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002257 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2258 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2259 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2260 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002261 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2262 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263
2264 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002265 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266
2267 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002268 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2269 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2270 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2271 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2272 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2273 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002274 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002275 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002277 // See if this is a device with keys. This could be full keyboard, or other devices like
2278 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002279 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002280 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2281 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2282 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002283 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2284 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2285 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002286 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002287 }
2288
2289 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002290 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2291 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002292 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294
Prabir Pradhana3621852022-10-14 18:57:23 +00002295 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002296 if (device->configuration) {
2297 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002298 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002299 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002300 } else if (deviceType == "externalStylus") {
2301 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002302 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002303 }
2304
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 // See if this is a touch pad.
2306 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002307 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002308 // Some joysticks such as the PS3 controller report axes that conflict
2309 // with the ABS_MT range. Try to confirm that the device really is
2310 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002311 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002312 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002313 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2314 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2315 device->classes |= InputDeviceClass::TOUCHPAD;
2316 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002317 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002318 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002319 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2320 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002321 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002322 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002323 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2324 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002325 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 }
2327
2328 // See if this device is a joystick.
2329 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2330 // from other devices such as accelerometers that also have absolute axes.
2331 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002332 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002333 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002334 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002335 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 device->classes = assumedClasses;
2337 break;
2338 }
2339 }
2340 }
2341
Chris Yef59a2f42020-10-16 12:55:26 -07002342 // Check whether this device is an accelerometer.
2343 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2344 device->classes |= InputDeviceClass::SENSOR;
2345 }
2346
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 // Check whether this device has switches.
2348 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002349 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002350 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 break;
2352 }
2353 }
2354
2355 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002356 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002357 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358 }
2359
2360 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002361 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 // Load the virtual keys for the touch screen, if any.
2363 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002364 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002365 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002366 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 }
2368 }
2369
2370 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002371 // We need to do this for joysticks too because the key layout may specify axes, and for
2372 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002373 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002374 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2375 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002377 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002378 }
2379
2380 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002381 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002383 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002384 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2385 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 mBuiltInKeyboardId = device->id;
2387 }
2388
2389 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002390 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002391 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 }
2393
2394 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002395 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2396 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2397 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2398 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2399 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002400 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
2402
2403 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002404 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002405 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002406 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 break;
2408 }
2409 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002410
2411 // See if this device has any stylus buttons that we would want to fuse with touch data.
2412 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2413 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2414 if (device->hasKeycodeLocked(keycode)) {
2415 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2416 break;
2417 }
2418 }
2419 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421
2422 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002423 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002424 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002425 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002426 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
2428
Chris Ye3fdbfef2021-01-06 18:45:18 -08002429 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002430 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002431 device->classes |= InputDeviceClass::BATTERY;
2432 }
Kim Low03ea0352020-11-06 12:45:07 -08002433
Chris Ye3fdbfef2021-01-06 18:45:18 -08002434 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002435 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002436 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002437 }
2438
Tim Kilbourn063ff532015-04-08 10:26:18 -07002439 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002440 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002441 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002442 }
2443
Michael Wrightd02c5b62014-02-10 15:10:22 -08002444 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002445 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002446 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 }
2448
Chris Ye1b0c7342020-07-28 21:57:03 -07002449 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2450 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002451 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2452 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002453 }
2454
Chris Ye989bb932020-07-04 16:18:59 -07002455 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002456 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 }
2458
Chris Ye989bb932020-07-04 16:18:59 -07002459 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002460
Chris Ye1b0c7342020-07-28 21:57:03 -07002461 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002462 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002463 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2464 device->classes.string().c_str(), device->configurationFile.c_str(),
2465 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2466 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002467
Chris Ye989bb932020-07-04 16:18:59 -07002468 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002469}
2470
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002471void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2472 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2473 if (!videoDevice) {
2474 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2475 return;
2476 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002477 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002478 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002479 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002480 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002481 }
2482 }
2483
2484 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2485 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002486 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002487 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002488 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2489}
2490
Chris Yed3fef462021-03-07 17:10:08 -08002491bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2492 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002493 if (videoDevice->getName() != device.identifier.name) {
2494 return false;
2495 }
2496 device.videoDevice = std::move(videoDevice);
2497 if (device.enabled) {
2498 registerVideoDeviceForEpollLocked(*device.videoDevice);
2499 }
2500 return true;
2501}
2502
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002503bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002504 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002505 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002506 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002507 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2508 return false;
2509 }
2510 return device->enabled;
2511}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002512
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002513status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002514 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002515 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002516 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002517 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2518 return BAD_VALUE;
2519 }
2520 if (device->enabled) {
2521 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2522 return OK;
2523 }
2524 status_t result = device->enable();
2525 if (result != OK) {
2526 ALOGE("Failed to enable device %" PRId32, deviceId);
2527 return result;
2528 }
2529
Chris Ye989bb932020-07-04 16:18:59 -07002530 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002531
Chris Ye989bb932020-07-04 16:18:59 -07002532 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002533}
2534
2535status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002536 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002537 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002538 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002539 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2540 return BAD_VALUE;
2541 }
2542 if (!device->enabled) {
2543 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2544 return OK;
2545 }
Chris Ye989bb932020-07-04 16:18:59 -07002546 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002547 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002548}
2549
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002550// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2551// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2552// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2553// directly observe UEvents instead of triggering from Java side.
2554void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2555 std::scoped_lock _l(mLock);
2556
2557 // Check in opening devices
2558 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2559 std::unique_ptr<Device>& device = *it;
2560 if (device->associatedDevice &&
2561 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2562 std::string::npos &&
2563 device->associatedDevice->isChanged()) {
2564 it = mOpeningDevices.erase(it);
2565 openDeviceLocked(device->path);
2566 }
2567 }
2568
2569 // Check in already added device
2570 std::vector<Device*> devicesToReopen;
2571 for (const auto& [id, device] : mDevices) {
2572 if (device->associatedDevice &&
2573 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2574 std::string::npos &&
2575 device->associatedDevice->isChanged()) {
2576 devicesToReopen.push_back(device.get());
2577 }
2578 }
2579 for (const auto& device : devicesToReopen) {
2580 closeDeviceLocked(*device);
2581 openDeviceLocked(device->path);
2582 }
2583 devicesToReopen.clear();
2584}
2585
Michael Wrightd02c5b62014-02-10 15:10:22 -08002586void EventHub::createVirtualKeyboardLocked() {
2587 InputDeviceIdentifier identifier;
2588 identifier.name = "Virtual";
2589 identifier.uniqueId = "<virtual>";
2590 assignDescriptorLocked(identifier);
2591
Chris Ye989bb932020-07-04 16:18:59 -07002592 std::unique_ptr<Device> device =
2593 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002594 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002595 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2596 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002597 device->loadKeyMapLocked();
2598 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002599}
2600
Chris Ye989bb932020-07-04 16:18:59 -07002601void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002602 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002603 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604}
2605
Chris Ye989bb932020-07-04 16:18:59 -07002606int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002607 if (mControllerNumbers.isFull()) {
2608 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002609 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 return 0;
2611 }
2612 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2613 // one
2614 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2615}
2616
Chris Ye989bb932020-07-04 16:18:59 -07002617void EventHub::releaseControllerNumberLocked(int32_t num) {
2618 if (num > 0) {
2619 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002621}
2622
Chris Ye8594e192020-07-14 10:34:06 -07002623void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002624 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002625 if (device != nullptr) {
2626 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002627 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628 }
Chris Ye8594e192020-07-14 10:34:06 -07002629 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002630}
2631
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002632/**
2633 * Find the video device by filename, and close it.
2634 * The video device is closed by path during an inotify event, where we don't have the
2635 * additional context about the video device fd, or the associated input device.
2636 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002637void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002638 // A video device may be owned by an existing input device, or it may be stored in
2639 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002640 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002641 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002642 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002643 device->videoDevice = nullptr;
2644 return;
2645 }
2646 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002647 std::erase_if(mUnattachedVideoDevices,
2648 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2649 return videoDevice->getPath() == devicePath;
2650 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651}
2652
2653void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002654 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002655 while (!mDevices.empty()) {
2656 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 }
2658}
2659
Chris Ye989bb932020-07-04 16:18:59 -07002660void EventHub::closeDeviceLocked(Device& device) {
2661 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2662 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663
Chris Ye989bb932020-07-04 16:18:59 -07002664 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002666 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2668 }
2669
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002670 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002671 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002672 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002673 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002674 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675
Chris Ye989bb932020-07-04 16:18:59 -07002676 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002677 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002678 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002679 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002680
Chris Ye989bb932020-07-04 16:18:59 -07002681 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682}
2683
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002684base::Result<void> EventHub::readNotifyLocked() {
2685 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2686 uint8_t eventBuffer[512];
2687 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688
2689 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002690 do {
2691 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2692 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002694 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2695
2696 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2697 const inotify_event* event;
2698 event = (const inotify_event*)(eventBuffer + eventPos);
2699 if (event->len == 0) continue;
2700
2701 handleNotifyEventLocked(*event);
2702
2703 const ssize_t eventSize = EVENT_SIZE + event->len;
2704 sizeRead -= eventSize;
2705 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002707 return {};
2708}
2709
2710void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2711 if (event.wd == mDeviceInputWd) {
2712 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2713 if (event.mask & IN_CREATE) {
2714 openDeviceLocked(filename);
2715 } else {
2716 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2717 closeDeviceByPathLocked(filename);
2718 }
2719 } else if (event.wd == mDeviceWd) {
2720 if (isV4lTouchNode(event.name)) {
2721 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2722 if (event.mask & IN_CREATE) {
2723 openVideoDeviceLocked(filename);
2724 } else {
2725 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2726 closeVideoDeviceByPathLocked(filename);
2727 }
2728 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2729 addDeviceInputInotify();
2730 }
2731 } else {
2732 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2733 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734}
2735
Chris Ye8594e192020-07-14 10:34:06 -07002736status_t EventHub::scanDirLocked(const std::string& dirname) {
2737 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2738 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740 return 0;
2741}
2742
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002743/**
2744 * Look for all dirname/v4l-touch* devices, and open them.
2745 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002746status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002747 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2748 if (isV4lTouchNode(entry.path())) {
2749 ALOGI("Found touch video device %s", entry.path().c_str());
2750 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002751 }
2752 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002753 return OK;
2754}
2755
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756void EventHub::requestReopenDevices() {
2757 ALOGV("requestReopenDevices() called");
2758
Chris Ye87143712020-11-10 05:05:58 +00002759 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760 mNeedToReopenDevices = true;
2761}
2762
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002763void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002764 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
2766 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002767 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002769 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002771 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
Chris Ye989bb932020-07-04 16:18:59 -07002773 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002775 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002776 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002778 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002779 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002781 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002782 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002783 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002784 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2785 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002786 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002787 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002788 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002789 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002790 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002791 device->identifier.product, device->identifier.version,
2792 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002793 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002794 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002795 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002796 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002797 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2798 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2799 device->associatedDevice->layoutInfo->languageTag.c_str());
2800 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2801 device->associatedDevice->layoutInfo->layoutType.c_str());
2802 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002803 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002804 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002805 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2806 device->videoDevice ? device->videoDevice->dump().c_str()
2807 : "<none>");
2808 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2809 device->associatedDevice
2810 ? device->associatedDevice->sysfsRootPath.c_str()
2811 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002813
2814 dump += INDENT "Unattached video devices:\n";
2815 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2816 dump += INDENT2 + videoDevice->dump() + "\n";
2817 }
2818 if (mUnattachedVideoDevices.empty()) {
2819 dump += INDENT2 "<none>\n";
2820 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 } // release lock
2822}
2823
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002824void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002826 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002827}
2828
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002829std::string EventHub::AssociatedDevice::dump() const {
2830 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2831 batteryInfos.size(), lightInfos.size());
2832}
2833
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002834} // namespace android