blob: 40e8628bdbe4d524d52638d9ace2aaf8c8518935 [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
Prabir Pradhanae10ee62023-05-12 19:44:18 +000061#include "KeyCodeClassifications.h"
62
Michael Wrightd02c5b62014-02-10 15:10:22 -080063#define INDENT " "
64#define INDENT2 " "
65#define INDENT3 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
Dominik Laskowski2f01d772022-03-23 16:01:29 -070071using namespace ftl::flag_operators;
72
Usama Arifb27c8e62021-06-03 16:44:09 +010073static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080074// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010075static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Chris Ye657c2f02021-05-25 16:24:37 -070077static constexpr size_t OBFUSCATED_LENGTH = 8;
78
Chris Ye87143712020-11-10 05:05:58 +000079static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
80static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070081
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070082static constexpr size_t EVENT_BUFFER_SIZE = 256;
83
Chris Yee2b1e5c2021-03-10 22:45:12 -080084// Mapping for input battery class node IDs lookup.
85// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
86static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
87 {{"capacity", InputBatteryClass::CAPACITY},
88 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
89 {"status", InputBatteryClass::STATUS}};
90
91// Mapping for input battery class node names lookup.
92// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
93static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
94 {{InputBatteryClass::CAPACITY, "capacity"},
95 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
96 {InputBatteryClass::STATUS, "status"}};
97
Kim Low03ea0352020-11-06 12:45:07 -080098// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
99static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
100 {{"Unknown", BATTERY_STATUS_UNKNOWN},
101 {"Charging", BATTERY_STATUS_CHARGING},
102 {"Discharging", BATTERY_STATUS_DISCHARGING},
103 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
104 {"Full", BATTERY_STATUS_FULL}};
105
106// Mapping taken from
107// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
108static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
109 {"Low", 10},
110 {"Normal", 55},
111 {"High", 70},
112 {"Full", 100},
113 {"Unknown", 50}};
114
Chris Ye3fdbfef2021-01-06 18:45:18 -0800115// Mapping for input led class node names lookup.
116// https://www.kernel.org/doc/html/latest/leds/leds-class.html
117static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
118 {{"red", InputLightClass::RED},
119 {"green", InputLightClass::GREEN},
120 {"blue", InputLightClass::BLUE},
121 {"global", InputLightClass::GLOBAL},
122 {"brightness", InputLightClass::BRIGHTNESS},
123 {"multi_index", InputLightClass::MULTI_INDEX},
124 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000125 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
126 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800127
128// Mapping for input multicolor led class node names.
129// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
130static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
131 {{InputLightClass::BRIGHTNESS, "brightness"},
132 {InputLightClass::MULTI_INDEX, "multi_index"},
133 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
134
135// Mapping for light color name and the light color
136const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
137 {"green", LightColor::GREEN},
138 {"blue", LightColor::BLUE}};
139
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000140// Mapping for country code to Layout info.
141// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
142const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
143 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
144 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
145 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
146 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
147 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
148 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
149 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
150 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
151 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
152 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
153 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
154 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
155 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
156 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
157 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
158 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
159 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
160 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
161 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
162 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
163 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
164 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
165 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
166 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
167 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
168 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
169 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
170 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
171 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
172 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
173 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
174 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
175 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
176 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
177 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
178 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
179
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100180static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700181 SHA_CTX ctx;
182 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100183 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700184 u_char digest[SHA_DIGEST_LENGTH];
185 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800186
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100187 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700188 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100189 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800190 }
191 return out;
192}
193
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800194/**
195 * Return true if name matches "v4l-touch*"
196 */
Chris Ye8594e192020-07-14 10:34:06 -0700197static bool isV4lTouchNode(std::string name) {
198 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800199}
200
Philip Quinn39b81682019-01-09 22:20:39 -0800201/**
202 * Returns true if V4L devices should be scanned.
203 *
204 * The system property ro.input.video_enabled can be used to control whether
205 * EventHub scans and opens V4L devices. As V4L does not support multiple
206 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700207 * them.
208 *
209 * Setting this to "false" would prevent any video devices from being discovered and
210 * associated with input devices.
211 *
212 * This property can be used as follows:
213 * 1. To turn off features that are dependent on video device presence.
214 * 2. During testing and development, to allow other clients to read video devices
215 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800216 */
217static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000218 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800219}
220
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800221static nsecs_t processEventTimestamp(const struct input_event& event) {
222 // Use the time specified in the event instead of the current time
223 // so that downstream code can get more accurate estimates of
224 // event dispatch latency from the time the event is enqueued onto
225 // the evdev client buffer.
226 //
227 // The event's timestamp fortuitously uses the same monotonic clock
228 // time base as the rest of Android. The kernel event device driver
229 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
230 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
231 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
232 // system call that also queries ktime_get_ts().
233
Colin Cross5b799302022-10-18 21:52:41 -0700234 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
235 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800236 return inputEventTime;
237}
238
Kim Low03ea0352020-11-06 12:45:07 -0800239/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000240 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800241 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800242static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800243 std::error_code errorCode;
244
245 // Stat the device path to get the major and minor number of the character file
246 struct stat statbuf;
247 if (stat(devicePath, &statbuf) == -1) {
248 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800249 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800250 }
251
252 unsigned int major_num = major(statbuf.st_rdev);
253 unsigned int minor_num = minor(statbuf.st_rdev);
254
255 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
256 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
257 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
258 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
259
260 // Make sure nothing went wrong in call to canonical()
261 if (errorCode) {
262 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
263 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800264 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800265 }
266
267 // Continue to go up a directory until we reach a directory named "input"
268 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
269 sysfsPath = sysfsPath.parent_path();
270 }
271
272 // Then go up one more and you will be at the sysfs root of the device
273 sysfsPath = sysfsPath.parent_path();
274
275 // Make sure we didn't reach root path and that directory actually exists
276 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
277 if (errorCode) {
278 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
279 errorCode.message().c_str());
280 }
281
282 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800283 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800284 }
285
286 return sysfsPath;
287}
288
289/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800290 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800291 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800292static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
293 std::vector<std::filesystem::path> nodes;
294 std::error_code errorCode;
295 auto iter = std::filesystem::directory_iterator(path, errorCode);
296 while (!errorCode && iter != std::filesystem::directory_iterator()) {
297 nodes.push_back(iter->path());
298 iter++;
299 }
300 return nodes;
301}
302
303/**
304 * Returns the list of files under a specified directory in a sysfs path.
305 * Example:
306 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
307 * in the sysfs path.
308 */
309static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
310 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800311 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800312 std::for_each(nodeStr.begin(), nodeStr.end(),
313 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
314 std::vector<std::filesystem::path> nodes;
315 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
316 nodes = allFilesInPath(path / nodeStr);
317 }
318 return nodes;
319}
320
321static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
322 std::filesystem::path path) {
323 std::string indexStr;
324 if (!base::ReadFileToString(path, &indexStr)) {
325 return std::nullopt;
326 }
327
328 // Parse the multi color LED index file, refer to kernel docs
329 // leds/leds-class-multicolor.html
330 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
331 std::smatch results;
332 std::array<LightColor, COLOR_NUM> colors;
333 if (!std::regex_match(indexStr, results, indexPattern)) {
334 return std::nullopt;
335 }
336
337 for (size_t i = 1; i < results.size(); i++) {
338 const auto it = LIGHT_COLORS.find(results[i].str());
339 if (it != LIGHT_COLORS.end()) {
340 // intensities.emplace(it->second, 0);
341 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800342 }
343 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800344 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800345}
346
Prabir Pradhancb42b472022-08-23 16:01:19 +0000347/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000348 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000349 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000350static std::optional<RawLayoutInfo> readLayoutConfiguration(
351 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000352 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000353 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000354 std::string str;
355 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
356 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000357 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000358 if (hidCountryCode > 35 || hidCountryCode < 0) {
359 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
360 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000361 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000362 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000363 const auto it = LAYOUT_INFOS.find(hidCountryCode);
364 if (it != LAYOUT_INFOS.end()) {
365 return it->second;
366 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000367
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000368 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000369}
370
371/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000372 * Read information about batteries exposed through the sysfs path.
373 */
374static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
375 const std::filesystem::path& sysfsRootPath) {
376 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
377 int32_t nextBatteryId = 0;
378 // Check if device has any battery.
379 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
380 for (const auto& nodePath : paths) {
381 RawBatteryInfo info;
382 info.id = ++nextBatteryId;
383 info.path = nodePath;
384 info.name = nodePath.filename();
385
386 // Scan the path for all the files
387 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
388 const auto& files = allFilesInPath(nodePath);
389 for (const auto& file : files) {
390 const auto it = BATTERY_CLASSES.find(file.filename().string());
391 if (it != BATTERY_CLASSES.end()) {
392 info.flags |= it->second;
393 }
394 }
395 batteryInfos.insert_or_assign(info.id, info);
396 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
397 }
398 return batteryInfos;
399}
400
401/**
402 * Read information about lights exposed through the sysfs path.
403 */
404static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
405 const std::filesystem::path& sysfsRootPath) {
406 std::unordered_map<int32_t, RawLightInfo> lightInfos;
407 int32_t nextLightId = 0;
408 // Check if device has any lights.
409 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
410 for (const auto& nodePath : paths) {
411 RawLightInfo info;
412 info.id = ++nextLightId;
413 info.path = nodePath;
414 info.name = nodePath.filename();
415 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000416
417 // Light name should follow the naming pattern <name>:<color>:<function>
418 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
419 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
420 std::smatch results;
421
422 if (std::regex_match(info.name, results, indexPattern)) {
423 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
424 // we only care about sections <color> and <function> which will be at index 2 and 3.
425 for (int i = 2; i <= 3; i++) {
426 const auto it = LIGHT_CLASSES.find(results.str(i));
427 if (it != LIGHT_CLASSES.end()) {
428 info.flags |= it->second;
429 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000430 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000431
432 // Set name of the raw light to <function> which represents playerIDs for LEDs that
433 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
434 // player ID logic)
435 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000436 }
437 // Scan the path for all the files
438 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
439 const auto& files = allFilesInPath(nodePath);
440 for (const auto& file : files) {
441 const auto it = LIGHT_CLASSES.find(file.filename().string());
442 if (it != LIGHT_CLASSES.end()) {
443 info.flags |= it->second;
444 // If the node has maximum brightness, read it
445 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
446 std::string str;
447 if (base::ReadFileToString(file, &str)) {
448 info.maxBrightness = std::stoi(str);
449 }
450 }
451 }
452 }
453 lightInfos.insert_or_assign(info.id, info);
454 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
455 }
456 return lightInfos;
457}
458
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459// --- Global Functions ---
460
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700461ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
462 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700464 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800465 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700466 case ABS_X:
467 case ABS_Y:
468 case ABS_PRESSURE:
469 case ABS_TOOL_WIDTH:
470 case ABS_DISTANCE:
471 case ABS_TILT_X:
472 case ABS_TILT_Y:
473 case ABS_MT_SLOT:
474 case ABS_MT_TOUCH_MAJOR:
475 case ABS_MT_TOUCH_MINOR:
476 case ABS_MT_WIDTH_MAJOR:
477 case ABS_MT_WIDTH_MINOR:
478 case ABS_MT_ORIENTATION:
479 case ABS_MT_POSITION_X:
480 case ABS_MT_POSITION_Y:
481 case ABS_MT_TOOL_TYPE:
482 case ABS_MT_BLOB_ID:
483 case ABS_MT_TRACKING_ID:
484 case ABS_MT_PRESSURE:
485 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700486 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487 }
488 }
489
Chris Yef59a2f42020-10-16 12:55:26 -0700490 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
491 switch (axis) {
492 case ABS_X:
493 case ABS_Y:
494 case ABS_Z:
495 case ABS_RX:
496 case ABS_RY:
497 case ABS_RZ:
498 return InputDeviceClass::SENSOR;
499 }
500 }
501
Michael Wright842500e2015-03-13 17:32:02 -0700502 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700503 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700504 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700505 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700506 }
507 }
508
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700510 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511}
512
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000513// --- RawAbsoluteAxisInfo ---
514
515std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
516 if (info.valid) {
517 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
518 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
519 } else {
520 out << "unknown range";
521 }
522 return out;
523}
524
Michael Wrightd02c5b62014-02-10 15:10:22 -0800525// --- EventHub::Device ---
526
Prabir Pradhancb42b472022-08-23 16:01:19 +0000527EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
528 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700529 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700530 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000531 path(std::move(path)),
532 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700533 classes(0),
534 configuration(nullptr),
535 virtualKeyMap(nullptr),
536 ffEffectPlaying(false),
537 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000538 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700539 controllerNumber(0),
540 enabled(true),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000541 isVirtual(fd < 0),
542 currentFrameDropped(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543
544EventHub::Device::~Device() {
545 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546}
547
548void EventHub::Device::close() {
549 if (fd >= 0) {
550 ::close(fd);
551 fd = -1;
552 }
553}
554
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700555status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100556 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700557 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100558 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700559 return -errno;
560 }
561 enabled = true;
562 return OK;
563}
564
565status_t EventHub::Device::disable() {
566 close();
567 enabled = false;
568 return OK;
569}
570
Chris Ye989bb932020-07-04 16:18:59 -0700571bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700572 return !isVirtual && enabled;
573}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574
Chris Ye3a1e4462020-08-12 10:13:15 -0700575const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700576 return keyMap.keyCharacterMap;
577}
578
579template <std::size_t N>
580status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
581 if (!hasValidFd()) {
582 return BAD_VALUE;
583 }
584 if ((_IOC_SIZE(ioctlCode) == 0)) {
585 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
586 }
587
588 typename BitArray<N>::Buffer buffer;
589 status_t ret = ioctl(fd, ioctlCode, buffer.data());
590 bitArray.loadFromBuffer(buffer);
591 return ret;
592}
593
594void EventHub::Device::configureFd() {
595 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
596 if (classes.test(InputDeviceClass::KEYBOARD)) {
597 // Disable kernel key repeat since we handle it ourselves
598 unsigned int repeatRate[] = {0, 0};
599 if (ioctl(fd, EVIOCSREP, repeatRate)) {
600 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
601 }
602 }
603
604 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
605 // associated with input events. This is important because the input system
606 // uses the timestamps extensively and assumes they were recorded using the monotonic
607 // clock.
608 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700609 if (classes.test(InputDeviceClass::SENSOR)) {
610 // Each new sensor event should use the same time base as
611 // SystemClock.elapsedRealtimeNanos().
612 clockId = CLOCK_BOOTTIME;
613 }
Chris Ye989bb932020-07-04 16:18:59 -0700614 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
615 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000616
617 // Query the initial state of keys and switches, which is tracked by EventHub.
618 readDeviceState();
619}
620
621void EventHub::Device::readDeviceState() {
622 if (readDeviceBitMask(EVIOCGKEY(0), keyState) < 0) {
623 ALOGD("Unable to query the global key state for %s: %s", path.c_str(), strerror(errno));
624 }
625 if (readDeviceBitMask(EVIOCGSW(0), swState) < 0) {
626 ALOGD("Unable to query the global switch state for %s: %s", path.c_str(), strerror(errno));
627 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000628
629 // Read absolute axis info and values for all available axes for the device.
630 populateAbsoluteAxisStates();
631}
632
633void EventHub::Device::populateAbsoluteAxisStates() {
634 absState.clear();
635
636 for (int axis = 0; axis <= ABS_MAX; axis++) {
637 if (!absBitmask.test(axis)) {
638 continue;
639 }
640 struct input_absinfo info {};
641 if (ioctl(fd, EVIOCGABS(axis), &info)) {
642 ALOGE("Error reading absolute controller %d for device %s fd %d: %s", axis,
643 identifier.name.c_str(), fd, strerror(errno));
644 continue;
645 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000646 auto& [axisInfo, value] = absState[axis];
647 axisInfo.valid = true;
648 axisInfo.minValue = info.minimum;
649 axisInfo.maxValue = info.maximum;
650 axisInfo.flat = info.flat;
651 axisInfo.fuzz = info.fuzz;
652 axisInfo.resolution = info.resolution;
653 value = info.value;
654 }
Chris Ye989bb932020-07-04 16:18:59 -0700655}
656
657bool EventHub::Device::hasKeycodeLocked(int keycode) const {
658 if (!keyMap.haveKeyLayout()) {
659 return false;
660 }
661
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700662 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700663 const size_t N = scanCodes.size();
664 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
665 int32_t sc = scanCodes[i];
666 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
667 return true;
668 }
669 }
670
Charles Linaadf8d52023-03-30 13:34:54 +0800671 std::vector<int32_t> usageCodes = keyMap.keyLayoutMap->findUsageCodesForKey(keycode);
672 if (usageCodes.size() > 0 && mscBitmask.test(MSC_SCAN)) {
673 return true;
674 }
675
Chris Ye989bb932020-07-04 16:18:59 -0700676 return false;
677}
678
679void EventHub::Device::loadConfigurationLocked() {
680 configurationFile =
681 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
682 InputDeviceConfigurationFileType::
683 CONFIGURATION);
684 if (configurationFile.empty()) {
685 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
686 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500687 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
688 PropertyMap::load(configurationFile.c_str());
689 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700690 ALOGE("Error loading input device configuration file for device '%s'. "
691 "Using default configuration.",
692 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500693 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500694 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700695 }
696 }
697}
698
699bool EventHub::Device::loadVirtualKeyMapLocked() {
700 // The virtual key map is supplied by the kernel as a system board property file.
701 std::string propPath = "/sys/board_properties/virtualkeys.";
702 propPath += identifier.getCanonicalName();
703 if (access(propPath.c_str(), R_OK)) {
704 return false;
705 }
706 virtualKeyMap = VirtualKeyMap::load(propPath);
707 return virtualKeyMap != nullptr;
708}
709
710status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500711 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700712}
713
714bool EventHub::Device::isExternalDeviceLocked() {
715 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000716 std::optional<bool> isInternal = configuration->getBool("device.internal");
717 if (isInternal.has_value()) {
718 return !isInternal.value();
Chris Ye989bb932020-07-04 16:18:59 -0700719 }
720 }
721 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
722}
723
724bool EventHub::Device::deviceHasMicLocked() {
725 if (configuration) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000726 std::optional<bool> hasMic = configuration->getBool("audio.mic");
727 if (hasMic.has_value()) {
728 return hasMic.value();
Chris Ye989bb932020-07-04 16:18:59 -0700729 }
730 }
731 return false;
732}
733
734void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
735 int32_t sc;
736 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
737 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700738 ev.input_event_sec = 0;
739 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700740 ev.type = EV_LED;
741 ev.code = sc;
742 ev.value = on ? 1 : 0;
743
744 ssize_t nWrite;
745 do {
746 nWrite = write(fd, &ev, sizeof(struct input_event));
747 } while (nWrite == -1 && errno == EINTR);
748 }
749}
750
751void EventHub::Device::setLedForControllerLocked() {
752 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
753 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
754 }
755}
756
757status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
758 if (!keyMap.haveKeyLayout()) {
759 return NAME_NOT_FOUND;
760 }
761
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700762 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
763 if (scanCode.has_value()) {
764 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
765 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700766 return NO_ERROR;
767 }
768 }
769 return NAME_NOT_FOUND;
770}
771
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000772void EventHub::Device::trackInputEvent(const struct input_event& event) {
773 switch (event.type) {
774 case EV_KEY: {
775 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
776 !keyState.set(static_cast<size_t>(event.code),
777 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000778 "%s: device '%s' received invalid EV_KEY event code: %s value: %d",
779 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000780 InputEventLookup::getLinuxEvdevLabel(EV_KEY, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000781 .code.c_str(),
782 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000783 break;
784 }
785 case EV_SW: {
786 LOG_ALWAYS_FATAL_IF(!currentFrameDropped &&
787 !swState.set(static_cast<size_t>(event.code),
788 event.value != 0),
Prabir Pradhan10301422023-07-26 21:48:30 +0000789 "%s: device '%s' received invalid EV_SW event code: %s value: %d",
790 __func__, identifier.name.c_str(),
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000791 InputEventLookup::getLinuxEvdevLabel(EV_SW, event.code, 1)
Prabir Pradhan10301422023-07-26 21:48:30 +0000792 .code.c_str(),
793 event.value);
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000794 break;
795 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000796 case EV_ABS: {
Prabir Pradhan10301422023-07-26 21:48:30 +0000797 if (currentFrameDropped) {
798 break;
799 }
Prabir Pradhan341d0782023-07-14 19:04:10 +0000800 auto it = absState.find(event.code);
Prabir Pradhan10301422023-07-26 21:48:30 +0000801 LOG_ALWAYS_FATAL_IF(it == absState.end(),
802 "%s: device '%s' received invalid EV_ABS event code: %s value: %d",
803 __func__, identifier.name.c_str(),
Prabir Pradhan341d0782023-07-14 19:04:10 +0000804 InputEventLookup::getLinuxEvdevLabel(EV_ABS, event.code, 0)
Prabir Pradhan10301422023-07-26 21:48:30 +0000805 .code.c_str(),
806 event.value);
Prabir Pradhan341d0782023-07-14 19:04:10 +0000807 it->second.value = event.value;
808 break;
809 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +0000810 case EV_SYN: {
811 switch (event.code) {
812 case SYN_REPORT:
813 currentFrameDropped = false;
814 break;
815 case SYN_DROPPED:
816 // When we receive SYN_DROPPED, all events in the current frame should be
817 // dropped. We query the state of the device to synchronize our device state
818 // with the kernel's to account for the dropped events.
819 currentFrameDropped = true;
820 readDeviceState();
821 break;
822 default:
823 break;
824 }
825 break;
826 }
827 default:
828 break;
829 }
830}
831
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100832/**
833 * Get the capabilities for the current process.
834 * Crashes the system if unable to create / check / destroy the capabilities object.
835 */
836class Capabilities final {
837public:
838 explicit Capabilities() {
839 mCaps = cap_get_proc();
840 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
841 }
842
843 /**
844 * Check whether the current process has a specific capability
845 * in the set of effective capabilities.
846 * Return CAP_SET if the process has the requested capability
847 * Return CAP_CLEAR otherwise.
848 */
849 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
850 cap_flag_value_t value;
851 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
852 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
853 return value;
854 }
855
856 ~Capabilities() {
857 const int result = cap_free(mCaps);
858 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
859 }
860
861private:
862 cap_t mCaps;
863};
864
865static void ensureProcessCanBlockSuspend() {
866 Capabilities capabilities;
867 const bool canBlockSuspend =
868 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
869 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
870 "Input must be able to block suspend to properly process events");
871}
872
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873// --- EventHub ---
874
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875const int EventHub::EPOLL_MAX_EVENTS;
876
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700877EventHub::EventHub(void)
878 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
879 mNextDeviceId(1),
880 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700882 mNeedToReopenDevices(false),
883 mNeedToScanDevices(true),
884 mPendingEventCount(0),
885 mPendingEventIndex(0),
886 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100887 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800889 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800890 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891
Michael Wright8e9a8562022-02-09 13:44:29 +0000892 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000893 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100894
895 std::error_code errorCode;
896 bool isDeviceInotifyAdded = false;
897 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
898 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800899 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100900 addDeviceInotify();
901 isDeviceInotifyAdded = true;
902 if (errorCode) {
903 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
904 errorCode.message().c_str());
905 }
906 }
907
908 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
909 addDeviceInotify();
910 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800911 ALOGI("Video device scanning disabled");
912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800913
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100914 struct epoll_event eventItem = {};
915 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700916 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800917 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800918 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
919
920 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000921 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800922 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
923
924 mWakeReadPipeFd = wakeFds[0];
925 mWakeWritePipeFd = wakeFds[1];
926
927 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
928 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700929 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930
931 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
932 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700933 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800934
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700935 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
937 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700938 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939}
940
941EventHub::~EventHub(void) {
942 closeAllDevicesLocked();
943
Michael Wrightd02c5b62014-02-10 15:10:22 -0800944 ::close(mEpollFd);
945 ::close(mINotifyFd);
946 ::close(mWakeReadPipeFd);
947 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800948}
949
Usama Arifb27c8e62021-06-03 16:44:09 +0100950/**
951 * On devices that don't have any input devices (like some development boards), the /dev/input
952 * directory will be absent. However, the user may still plug in an input device at a later time.
953 * Add watch for contents of /dev/input only when /dev/input appears.
954 */
955void EventHub::addDeviceInputInotify() {
956 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
957 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
958 DEVICE_INPUT_PATH, strerror(errno));
959}
960
961void EventHub::addDeviceInotify() {
962 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
963 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
964 strerror(errno));
965}
966
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000968 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800969 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700970 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971}
972
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700973ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000974 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800975 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700976 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977}
978
979int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000980 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700982 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983}
984
Harry Cuttsc34f7582023-03-07 16:23:30 +0000985std::optional<PropertyMap> EventHub::getConfiguration(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000986 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 Device* device = getDeviceLocked(deviceId);
Harry Cuttsc34f7582023-03-07 16:23:30 +0000988 if (device == nullptr || device->configuration == nullptr) {
989 return {};
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 }
Harry Cuttsc34f7582023-03-07 16:23:30 +0000991 return *device->configuration;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992}
993
994status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700995 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800996 outAxisInfo->clear();
Arpit Singh77140f42023-06-13 11:35:27 +0000997 if (axis < 0 || axis > ABS_MAX) {
Prabir Pradhan341d0782023-07-14 19:04:10 +0000998 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800999 }
Arpit Singh77140f42023-06-13 11:35:27 +00001000 std::scoped_lock _l(mLock);
Prabir Pradhan341d0782023-07-14 19:04:10 +00001001 const Device* device = getDeviceLocked(deviceId);
Arpit Singh77140f42023-06-13 11:35:27 +00001002 if (device == nullptr) {
Prabir Pradhan341d0782023-07-14 19:04:10 +00001003 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001004 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001005 // We can read the RawAbsoluteAxisInfo even if the device is disabled and doesn't have a valid
1006 // fd, because the info is populated once when the device is first opened, and it doesn't change
1007 // throughout the device lifecycle.
1008 auto it = device->absState.find(axis);
1009 if (it == device->absState.end()) {
1010 return NAME_NOT_FOUND;
Arpit Singh77140f42023-06-13 11:35:27 +00001011 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001012 *outAxisInfo = it->second.info;
Arpit Singh77140f42023-06-13 11:35:27 +00001013 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001014}
1015
1016bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
1017 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001018 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001020 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 }
1022 return false;
1023}
1024
1025bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +00001026 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027
Chris Ye989bb932020-07-04 16:18:59 -07001028 Device* device = getDeviceLocked(deviceId);
1029 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
1030 ? device->propBitmask.test(property)
1031 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001032}
1033
Chris Yef59a2f42020-10-16 12:55:26 -07001034bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
1035 std::scoped_lock _l(mLock);
1036
1037 Device* device = getDeviceLocked(deviceId);
1038 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
1039 ? device->mscBitmask.test(mscEvent)
1040 : false;
1041}
1042
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001044 if (scanCode < 0 || scanCode > KEY_MAX) {
1045 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001047 std::scoped_lock _l(mLock);
1048 const Device* device = getDeviceLocked(deviceId);
1049 if (device == nullptr || !device->hasValidFd() || !device->keyBitmask.test(scanCode)) {
1050 return AKEY_STATE_UNKNOWN;
1051 }
1052 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053}
1054
1055int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001056 std::scoped_lock _l(mLock);
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001057 const Device* device = getDeviceLocked(deviceId);
1058 if (device == nullptr || !device->hasValidFd() || !device->keyMap.haveKeyLayout()) {
1059 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001060 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001061 const std::vector<int32_t> scanCodes =
1062 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
1063 if (scanCodes.empty()) {
1064 return AKEY_STATE_UNKNOWN;
1065 }
1066 return std::any_of(scanCodes.begin(), scanCodes.end(),
1067 [&device](const int32_t sc) {
1068 return sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc);
1069 })
1070 ? AKEY_STATE_DOWN
1071 : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072}
1073
Philip Junker4af3b3d2021-12-14 10:36:55 +01001074int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
1075 std::scoped_lock _l(mLock);
1076
1077 Device* device = getDeviceLocked(deviceId);
1078 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
1079 device->keyMap.keyLayoutMap == nullptr) {
1080 return AKEYCODE_UNKNOWN;
1081 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001082 std::vector<int32_t> scanCodes =
1083 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001084 if (scanCodes.empty()) {
1085 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
1086 "device %d",
1087 locationKeyCode, deviceId);
1088 return AKEYCODE_UNKNOWN;
1089 }
1090 if (scanCodes.size() > 1) {
1091 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1092 locationKeyCode);
1093 }
1094 int32_t outKeyCode;
1095 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001096 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001097 switch (mapKeyRes) {
1098 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001099 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001100 case NAME_NOT_FOUND:
1101 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001102 outKeyCode = locationKeyCode;
1103 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001104 default:
1105 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1106 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001107 outKeyCode = AKEYCODE_UNKNOWN;
1108 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001109 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001110 // Remap if there is a Key remapping added to the KCM and return the remapped key
1111 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001112}
1113
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001115 if (sw < 0 || sw > SW_MAX) {
1116 return AKEY_STATE_UNKNOWN;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 }
Prabir Pradhan9762ac92023-07-13 21:45:12 +00001118 std::scoped_lock _l(mLock);
1119 const Device* device = getDeviceLocked(deviceId);
1120 if (device == nullptr || !device->hasValidFd() || !device->swBitmask.test(sw)) {
1121 return AKEY_STATE_UNKNOWN;
1122 }
1123 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124}
1125
1126status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1127 *outValue = 0;
Prabir Pradhan341d0782023-07-14 19:04:10 +00001128 if (axis < 0 || axis > ABS_MAX) {
1129 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 }
Prabir Pradhan341d0782023-07-14 19:04:10 +00001131 std::scoped_lock _l(mLock);
1132 const Device* device = getDeviceLocked(deviceId);
1133 if (device == nullptr || !device->hasValidFd()) {
1134 return NAME_NOT_FOUND;
1135 }
1136 const auto it = device->absState.find(axis);
1137 if (it == device->absState.end()) {
1138 return NAME_NOT_FOUND;
1139 }
1140 *outValue = it->second.value;
1141 return OK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142}
1143
Arpit Singh4b4a4572023-11-24 18:19:56 +00001144base::Result<std::vector<int32_t>> EventHub::getMtSlotValues(int32_t deviceId, int32_t axis,
1145 size_t slotCount) const {
1146 std::scoped_lock _l(mLock);
1147 const Device* device = getDeviceLocked(deviceId);
1148 if (device == nullptr || !device->hasValidFd() || !device->absBitmask.test(axis)) {
1149 return base::ResultError("device problem or axis not supported", NAME_NOT_FOUND);
1150 }
1151 std::vector<int32_t> outValues(slotCount + 1);
1152 outValues[0] = axis;
1153 const size_t bufferSize = outValues.size() * sizeof(int32_t);
1154 if (ioctl(device->fd, EVIOCGMTSLOTS(bufferSize), outValues.data()) != OK) {
1155 return base::ErrnoError();
1156 }
1157 return std::move(outValues);
1158}
1159
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001160bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001161 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001162 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163
1164 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001165 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001166 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Sergej Salnikove5420e72023-05-11 11:52:54 +00001167 if (device->hasKeycodeLocked(keyCodes[codeIndex])) {
1168 outFlags[codeIndex] = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001169 }
1170 }
1171 return true;
1172 }
1173 return false;
1174}
1175
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001176void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1177 std::scoped_lock _l(mLock);
1178 Device* device = getDeviceLocked(deviceId);
1179 if (device == nullptr) {
1180 return;
1181 }
1182 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1183 if (kcm) {
1184 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1185 }
1186}
1187
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001188status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1189 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001190 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001192 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001193
Chris Ye66fbac32020-07-06 20:36:43 -07001194 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001195 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001196 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1197 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1199 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001200 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 }
1202 }
1203
1204 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001205 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001206 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001207 status = NO_ERROR;
1208 }
1209 }
1210
1211 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001212 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001213 // Remap keys based on user-defined key remappings and key behavior defined in the
1214 // corresponding kcm file
1215 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1216
1217 // Remap keys based on Key behavior defined in KCM file
1218 std::tie(*outKeycode, *outMetaState) =
1219 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001220 } else {
1221 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 }
1223 }
1224 }
1225
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001226 if (status != NO_ERROR) {
1227 *outKeycode = 0;
1228 *outFlags = 0;
1229 *outMetaState = metaState;
1230 }
1231
1232 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233}
1234
1235status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001236 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001237 Device* device = getDeviceLocked(deviceId);
1238
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001239 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1240 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001242 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1243 if (!info.has_value()) {
1244 return NAME_NOT_FOUND;
1245 }
1246 *outAxisInfo = *info;
1247 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248}
1249
Chris Yef59a2f42020-10-16 12:55:26 -07001250base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001251 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001252 std::scoped_lock _l(mLock);
1253 Device* device = getDeviceLocked(deviceId);
1254
1255 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1256 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1257 }
1258 return Errorf("Device not found or device has no key layout.");
1259}
1260
Chris Yee2b1e5c2021-03-10 22:45:12 -08001261// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1262// associated with the device ID. Returns an empty map if no miscellaneous device found.
1263const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1264 int32_t deviceId) const {
1265 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1266 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001267 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001268 return EMPTY_BATTERY_INFO;
1269 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001270 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001271}
1272
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001273std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001274 std::scoped_lock _l(mLock);
1275 std::vector<int32_t> batteryIds;
1276
Prabir Pradhan51894782022-08-23 16:29:10 +00001277 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001278 batteryIds.push_back(id);
1279 }
1280
1281 return batteryIds;
1282}
1283
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001284std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1285 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001286 std::scoped_lock _l(mLock);
1287
1288 const auto infos = getBatteryInfoLocked(deviceId);
1289
1290 auto it = infos.find(batteryId);
1291 if (it != infos.end()) {
1292 return it->second;
1293 }
1294
1295 return std::nullopt;
1296}
1297
1298// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001299// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001300const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1301 int32_t deviceId) const {
1302 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1303 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001304 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001305 return EMPTY_LIGHT_INFO;
1306 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001307 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001308}
1309
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001310std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001311 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001312 std::vector<int32_t> lightIds;
1313
Prabir Pradhan51894782022-08-23 16:29:10 +00001314 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001315 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001316 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001317
Chris Ye3fdbfef2021-01-06 18:45:18 -08001318 return lightIds;
1319}
1320
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001321std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001322 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001323
Chris Yee2b1e5c2021-03-10 22:45:12 -08001324 const auto infos = getLightInfoLocked(deviceId);
1325
1326 auto it = infos.find(lightId);
1327 if (it != infos.end()) {
1328 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001329 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001330
Chris Ye3fdbfef2021-01-06 18:45:18 -08001331 return std::nullopt;
1332}
1333
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001334std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001335 std::scoped_lock _l(mLock);
1336
Chris Yee2b1e5c2021-03-10 22:45:12 -08001337 const auto infos = getLightInfoLocked(deviceId);
1338 auto it = infos.find(lightId);
1339 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001340 return std::nullopt;
1341 }
1342 std::string buffer;
1343 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1344 &buffer)) {
1345 return std::nullopt;
1346 }
1347 return std::stoi(buffer);
1348}
1349
1350std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001351 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001352 std::scoped_lock _l(mLock);
1353
Chris Yee2b1e5c2021-03-10 22:45:12 -08001354 const auto infos = getLightInfoLocked(deviceId);
1355 auto lightIt = infos.find(lightId);
1356 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001357 return std::nullopt;
1358 }
1359
1360 auto ret =
1361 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1362
1363 if (!ret.has_value()) {
1364 return std::nullopt;
1365 }
1366 std::array<LightColor, COLOR_NUM> colors = ret.value();
1367
1368 std::string intensityStr;
1369 if (!base::ReadFileToString(lightIt->second.path /
1370 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1371 &intensityStr)) {
1372 return std::nullopt;
1373 }
1374
1375 // Intensity node outputs 3 color values
1376 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1377 std::smatch results;
1378
1379 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1380 return std::nullopt;
1381 }
1382 std::unordered_map<LightColor, int32_t> intensities;
1383 for (size_t i = 1; i < results.size(); i++) {
1384 int value = std::stoi(results[i].str());
1385 intensities.emplace(colors[i - 1], value);
1386 }
1387 return intensities;
1388}
1389
1390void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1391 std::scoped_lock _l(mLock);
1392
Chris Yee2b1e5c2021-03-10 22:45:12 -08001393 const auto infos = getLightInfoLocked(deviceId);
1394 auto lightIt = infos.find(lightId);
1395 if (lightIt == infos.end()) {
1396 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001397 return;
1398 }
1399
1400 if (!base::WriteStringToFile(std::to_string(brightness),
1401 lightIt->second.path /
1402 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1403 ALOGE("Can not write to file, error: %s", strerror(errno));
1404 }
1405}
1406
1407void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1408 std::unordered_map<LightColor, int32_t> intensities) {
1409 std::scoped_lock _l(mLock);
1410
Chris Yee2b1e5c2021-03-10 22:45:12 -08001411 const auto infos = getLightInfoLocked(deviceId);
1412 auto lightIt = infos.find(lightId);
1413 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001414 ALOGE("Light Id %d does not exist.", lightId);
1415 return;
1416 }
1417
1418 auto ret =
1419 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1420
1421 if (!ret.has_value()) {
1422 return;
1423 }
1424 std::array<LightColor, COLOR_NUM> colors = ret.value();
1425
1426 std::string rgbStr;
1427 for (size_t i = 0; i < COLOR_NUM; i++) {
1428 auto it = intensities.find(colors[i]);
1429 if (it != intensities.end()) {
1430 rgbStr += std::to_string(it->second);
1431 // Insert space between colors
1432 if (i < COLOR_NUM - 1) {
1433 rgbStr += " ";
1434 }
1435 }
1436 }
1437 // Append new line
1438 rgbStr += "\n";
1439
1440 if (!base::WriteStringToFile(rgbStr,
1441 lightIt->second.path /
1442 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1443 ALOGE("Can not write to file, error: %s", strerror(errno));
1444 }
1445}
1446
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001447std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001448 std::scoped_lock _l(mLock);
1449 Device* device = getDeviceLocked(deviceId);
1450 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001451 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001452 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001453 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001454}
1455
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001456void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001457 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001458
1459 mExcludedDevices = devices;
1460}
1461
1462bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001463 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001465 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1466 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001467 }
1468 return false;
1469}
1470
Arthur Hungcb40a002021-08-03 14:31:01 +00001471bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1472 std::scoped_lock _l(mLock);
1473 Device* device = getDeviceLocked(deviceId);
1474 if (device != nullptr) {
1475 return device->hasKeycodeLocked(keyCode);
1476 }
1477 return false;
1478}
1479
Michael Wrightd02c5b62014-02-10 15:10:22 -08001480bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001481 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482 Device* device = getDeviceLocked(deviceId);
1483 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001484 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001485 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001486 }
1487 return false;
1488}
1489
1490void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001491 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001492 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001493 if (device != nullptr && device->hasValidFd()) {
1494 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001495 }
1496}
1497
1498void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001499 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 outVirtualKeys.clear();
1501
Chris Ye87143712020-11-10 05:05:58 +00001502 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001504 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001505 const std::vector<VirtualKeyDefinition> virtualKeys =
1506 device->virtualKeyMap->getVirtualKeys();
1507 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001508 }
1509}
1510
Chris Ye3a1e4462020-08-12 10:13:15 -07001511const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001512 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001513 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001514 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001515 return device->getKeyCharacterMap();
1516 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001517 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001518}
1519
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001520// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001521bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001522 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001523 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001524 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001525 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001526 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001527 if (map == nullptr) {
1528 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1529 return true;
1530 }
Philip Junker90bc9492021-12-10 18:39:42 +01001531 device->keyMap.keyCharacterMap->combine(*map);
1532 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533}
1534
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001535static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1536 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001537 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001539 if (!identifier.uniqueId.empty()) {
1540 rawDescriptor += "uniqueId:";
1541 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001542 }
1543 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001544 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001545 }
1546
1547 if (identifier.vendor == 0 && identifier.product == 0) {
1548 // If we don't know the vendor and product id, then the device is probably
1549 // built-in so we need to rely on other information to uniquely identify
1550 // the input device. Usually we try to avoid relying on the device name or
1551 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001552 if (!identifier.name.empty()) {
1553 rawDescriptor += "name:";
1554 rawDescriptor += identifier.name;
1555 } else if (!identifier.location.empty()) {
1556 rawDescriptor += "location:";
1557 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001558 }
1559 }
1560 identifier.descriptor = sha1(rawDescriptor);
1561 return rawDescriptor;
1562}
1563
1564void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1565 // Compute a device descriptor that uniquely identifies the device.
1566 // The descriptor is assumed to be a stable identifier. Its value should not
1567 // change between reboots, reconnections, firmware updates or new releases
1568 // of Android. In practice we sometimes get devices that cannot be uniquely
1569 // identified. In this case we enforce uniqueness between connected devices.
1570 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001571 // Note that we explicitly do not use the path or location for external devices
1572 // as their path or location will change as they are plugged/unplugged or moved
1573 // to different ports. We do fallback to using name and location in the case of
1574 // internal devices which are detected by the vendor and product being 0 in
1575 // generateDescriptor. If two identical descriptors are detected we will fallback
1576 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1577 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001578
1579 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001580 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001581 // Enforce that the generated descriptor is unique.
1582 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1583 identifier.nonce++;
1584 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001586 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001587 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588}
1589
Prabir Pradhancb42b472022-08-23 16:01:19 +00001590std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1591 const std::filesystem::path& devicePath) const {
1592 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1593 getSysfsRootPath(devicePath.c_str());
1594 if (!sysfsRootPathOpt) {
1595 return nullptr;
1596 }
1597
1598 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001599
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001600 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001601 AssociatedDevice{.sysfsRootPath = path,
1602 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001603 .lightInfos = readLightsConfiguration(path),
1604 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001605
1606 bool associatedDeviceChanged = false;
1607 for (const auto& [id, dev] : mDevices) {
1608 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1609 if (*associatedDevice != *dev->associatedDevice) {
1610 associatedDeviceChanged = true;
1611 dev->associatedDevice = associatedDevice;
1612 }
1613 associatedDevice = dev->associatedDevice;
1614 }
1615 }
1616 ALOGI_IF(associatedDeviceChanged,
1617 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1618 path.c_str(), associatedDevice->dump().c_str());
1619
1620 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001621}
1622
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00001623bool EventHub::AssociatedDevice::isChanged() const {
1624 std::unordered_map<int32_t, RawBatteryInfo> newBatteryInfos =
1625 readBatteryConfiguration(sysfsRootPath);
1626 std::unordered_map<int32_t, RawLightInfo> newLightInfos =
1627 readLightsConfiguration(sysfsRootPath);
1628 std::optional<RawLayoutInfo> newLayoutInfo = readLayoutConfiguration(sysfsRootPath);
1629
1630 if (newBatteryInfos == batteryInfos && newLightInfos == lightInfos &&
1631 newLayoutInfo == layoutInfo) {
1632 return false;
1633 }
1634 return true;
1635}
1636
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001637void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001638 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001639 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001640 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001641 ff_effect effect;
1642 memset(&effect, 0, sizeof(effect));
1643 effect.type = FF_RUMBLE;
1644 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001645 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001646 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1647 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001648 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001649 effect.replay.delay = 0;
1650 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1651 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001652 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001653 return;
1654 }
1655 device->ffEffectId = effect.id;
1656
1657 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001658 ev.input_event_sec = 0;
1659 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001660 ev.type = EV_FF;
1661 ev.code = device->ffEffectId;
1662 ev.value = 1;
1663 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1664 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001665 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001666 return;
1667 }
1668 device->ffEffectPlaying = true;
1669 }
1670}
1671
1672void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001673 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001674 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001675 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001676 if (device->ffEffectPlaying) {
1677 device->ffEffectPlaying = false;
1678
1679 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001680 ev.input_event_sec = 0;
1681 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001682 ev.type = EV_FF;
1683 ev.code = device->ffEffectId;
1684 ev.value = 0;
1685 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1686 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001687 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001688 return;
1689 }
1690 }
1691 }
1692}
1693
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001694std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001695 std::scoped_lock _l(mLock);
1696 std::vector<int32_t> vibrators;
1697 Device* device = getDeviceLocked(deviceId);
1698 if (device != nullptr && device->hasValidFd() &&
1699 device->classes.test(InputDeviceClass::VIBRATOR)) {
1700 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1701 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1702 }
1703 return vibrators;
1704}
1705
Josh Bartel938632f2022-07-19 15:34:22 -05001706/**
1707 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1708 */
1709bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1710 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001711 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001712 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001713 }
1714 }
Josh Bartel938632f2022-07-19 15:34:22 -05001715
1716 for (const auto& [id, device] : mDevices) {
1717 if (descriptor == device->identifier.descriptor) {
1718 return true;
1719 }
1720 }
1721 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722}
1723
1724EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001725 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001726 deviceId = mBuiltInKeyboardId;
1727 }
Chris Ye989bb932020-07-04 16:18:59 -07001728 const auto& it = mDevices.find(deviceId);
1729 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001730}
1731
Chris Ye8594e192020-07-14 10:34:06 -07001732EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001733 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001734 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001735 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001736 }
1737 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001738 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001739}
1740
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001741/**
1742 * The file descriptor could be either input device, or a video device (associated with a
1743 * specific input device). Check both cases here, and return the device that this event
1744 * belongs to. Caller can compare the fd's once more to determine event type.
1745 * Looks through all input devices, and only attached video devices. Unattached video
1746 * devices are ignored.
1747 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001748EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001749 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001750 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001751 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001752 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001753 }
1754 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1755 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001756 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001757 }
1758 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001759 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1760 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001761 return nullptr;
1762}
1763
Chris Yee2b1e5c2021-03-10 22:45:12 -08001764std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001765 std::filesystem::path batteryPath;
1766 {
1767 // Do not read the sysfs node to get the battery state while holding
1768 // the EventHub lock. For some peripheral devices, reading battery state
1769 // can be broken and take 5+ seconds. Holding the lock in this case would
1770 // block all other event processing during this time. For now, we assume this
1771 // call never happens on the InputReader thread and read the sysfs node outside
1772 // the lock to prevent event processing from being blocked by this call.
1773 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001774
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001775 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001776 auto it = infos.find(batteryId);
1777 if (it == infos.end()) {
1778 return std::nullopt;
1779 }
1780 batteryPath = it->second.path;
1781 } // release lock
1782
Chris Yee2b1e5c2021-03-10 22:45:12 -08001783 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001784
1785 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001786 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001787 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001788 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001789 }
1790
1791 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1792 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001793 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001794 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001795 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001796 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1797 if (levelIt != BATTERY_LEVEL.end()) {
1798 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001799 }
1800 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001801
Kim Low03ea0352020-11-06 12:45:07 -08001802 return std::nullopt;
1803}
1804
Chris Yee2b1e5c2021-03-10 22:45:12 -08001805std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001806 std::filesystem::path batteryPath;
1807 {
1808 // Do not read the sysfs node to get the battery state while holding
1809 // the EventHub lock. For some peripheral devices, reading battery state
1810 // can be broken and take 5+ seconds. Holding the lock in this case would
1811 // block all other event processing during this time. For now, we assume this
1812 // call never happens on the InputReader thread and read the sysfs node outside
1813 // the lock to prevent event processing from being blocked by this call.
1814 std::scoped_lock _l(mLock);
1815
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001816 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001817 auto it = infos.find(batteryId);
1818 if (it == infos.end()) {
1819 return std::nullopt;
1820 }
1821 batteryPath = it->second.path;
1822 } // release lock
1823
Chris Yee2b1e5c2021-03-10 22:45:12 -08001824 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001825
Andy Chenf9f1a022022-08-29 20:07:10 -04001826 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001827 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001828 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1829 return std::nullopt;
1830 }
1831
Chris Yed1936772021-02-22 10:30:40 -08001832 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001833 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1834 if (statusIt != BATTERY_STATUS.end()) {
1835 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001836 }
1837
1838 return std::nullopt;
1839}
1840
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001841std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001842 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001843
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001844 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001846 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001847 bool awoken = false;
1848 for (;;) {
1849 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1850
1851 // Reopen input devices if needed.
1852 if (mNeedToReopenDevices) {
1853 mNeedToReopenDevices = false;
1854
1855 ALOGI("Reopening all input devices due to a configuration change.");
1856
1857 closeAllDevicesLocked();
1858 mNeedToScanDevices = true;
1859 break; // return to the caller before we actually rescan
1860 }
1861
1862 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001863 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1864 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001865 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001866 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001867 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1868 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001869 events.push_back({
1870 .when = now,
1871 .deviceId = deviceId,
1872 .type = DEVICE_REMOVED,
1873 });
Chris Ye989bb932020-07-04 16:18:59 -07001874 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001875 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001876 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001877 break;
1878 }
1879 }
1880
1881 if (mNeedToScanDevices) {
1882 mNeedToScanDevices = false;
1883 scanDevicesLocked();
1884 mNeedToSendFinishedDeviceScan = true;
1885 }
1886
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001887 while (!mOpeningDevices.empty()) {
1888 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1889 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001890 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001891 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1892 events.push_back({
1893 .when = now,
1894 .deviceId = deviceId,
1895 .type = DEVICE_ADDED,
1896 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001897
1898 // Try to find a matching video device by comparing device names
1899 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1900 it++) {
1901 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001902 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001903 // videoDevice was transferred to 'device'
1904 it = mUnattachedVideoDevices.erase(it);
1905 break;
1906 }
1907 }
1908
1909 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1910 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001911 ALOGW("Device id %d exists, replaced.", device->id);
1912 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001913 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001914 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 break;
1916 }
1917 }
1918
1919 if (mNeedToSendFinishedDeviceScan) {
1920 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001921 events.push_back({
1922 .when = now,
1923 .type = FINISHED_DEVICE_SCAN,
1924 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001925 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 break;
1927 }
1928 }
1929
1930 // Grab the next input event.
1931 bool deviceChanged = false;
1932 while (mPendingEventIndex < mPendingEventCount) {
1933 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001934 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001935 if (eventItem.events & EPOLLIN) {
1936 mPendingINotify = true;
1937 } else {
1938 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1939 }
1940 continue;
1941 }
1942
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001943 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001944 if (eventItem.events & EPOLLIN) {
1945 ALOGV("awoken after wake()");
1946 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001947 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001948 ssize_t nRead;
1949 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001950 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1951 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001952 } else {
1953 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001954 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001955 }
1956 continue;
1957 }
1958
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001959 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001960 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001961 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1962 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001963 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 continue;
1965 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001966 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1967 if (eventItem.events & EPOLLIN) {
1968 size_t numFrames = device->videoDevice->readAndQueueFrames();
1969 if (numFrames == 0) {
1970 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001971 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001972 }
1973 } else if (eventItem.events & EPOLLHUP) {
1974 // TODO(b/121395353) - consider adding EPOLLRDHUP
1975 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001976 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001977 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1978 device->videoDevice = nullptr;
1979 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001980 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1981 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001982 ALOG_ASSERT(!DEBUG);
1983 }
1984 continue;
1985 }
1986 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001988 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001989 read(device->fd, readBuffer.data(),
1990 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1992 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001993 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001994 " capacity: %zu errno: %d)\n",
1995 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001996 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001997 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001998 } else if (readSize < 0) {
1999 if (errno != EAGAIN && errno != EINTR) {
2000 ALOGW("could not get event (errno=%d)", errno);
2001 }
2002 } else if ((readSize % sizeof(struct input_event)) != 0) {
2003 ALOGE("could not get event (wrong size: %d)", readSize);
2004 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002005 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002007 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 for (size_t i = 0; i < count; i++) {
2009 struct input_event& iev = readBuffer[i];
Prabir Pradhan9762ac92023-07-13 21:45:12 +00002010 device->trackInputEvent(iev);
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002011 events.push_back({
2012 .when = processEventTimestamp(iev),
2013 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
2014 .deviceId = deviceId,
2015 .type = iev.type,
2016 .code = iev.code,
2017 .value = iev.value,
2018 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07002020 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 // The result buffer is full. Reset the pending event index
2022 // so we will try to read the device again on the next iteration.
2023 mPendingEventIndex -= 1;
2024 break;
2025 }
2026 }
2027 } else if (eventItem.events & EPOLLHUP) {
2028 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002029 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07002031 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002032 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002033 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
2034 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036 }
2037
2038 // readNotify() will modify the list of devices so this must be done after
2039 // processing all other events to ensure that we read all remaining events
2040 // before closing the devices.
2041 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
2042 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002043 const auto res = readNotifyLocked();
2044 if (!res.ok()) {
2045 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
2046 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 deviceChanged = true;
2048 }
2049
2050 // Report added or removed devices immediately.
2051 if (deviceChanged) {
2052 continue;
2053 }
2054
2055 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002056 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 break;
2058 }
2059
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002060 // Poll for events.
2061 // When a device driver has pending (unread) events, it acquires
2062 // a kernel wake lock. Once the last pending event has been read, the device
2063 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
2064 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
2065 // is called again for the same fd that produced the event.
2066 // Thus the system can only sleep if there are no events pending or
2067 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002068 //
2069 // The timeout is advisory only. If the device is asleep, it will not wake just to
2070 // service the timeout.
2071 mPendingEventIndex = 0;
2072
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002073 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074
2075 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
2076
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01002077 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08002078
2079 if (pollResult == 0) {
2080 // Timed out.
2081 mPendingEventCount = 0;
2082 break;
2083 }
2084
2085 if (pollResult < 0) {
2086 // An error occurred.
2087 mPendingEventCount = 0;
2088
2089 // Sleep after errors to avoid locking up the system.
2090 // Hopefully the error is transient.
2091 if (errno != EINTR) {
2092 ALOGW("poll failed (errno=%d)\n", errno);
2093 usleep(100000);
2094 }
2095 } else {
2096 // Some events occurred.
2097 mPendingEventCount = size_t(pollResult);
2098 }
2099 }
2100
2101 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07002102 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103}
2104
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002105std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002106 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002107
2108 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002109 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002110 return {};
2111 }
2112 return device->videoDevice->consumeFrames();
2113}
2114
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115void EventHub::wake() {
2116 ALOGV("wake() called");
2117
2118 ssize_t nWrite;
2119 do {
2120 nWrite = write(mWakeWritePipeFd, "W", 1);
2121 } while (nWrite == -1 && errno == EINTR);
2122
2123 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002124 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002125 }
2126}
2127
2128void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002129 status_t result;
2130 std::error_code errorCode;
2131
2132 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2133 result = scanDirLocked(DEVICE_INPUT_PATH);
2134 if (result < 0) {
2135 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2136 }
2137 } else {
2138 if (errorCode) {
2139 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2140 errorCode.message().c_str());
2141 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002142 }
Philip Quinn39b81682019-01-09 22:20:39 -08002143 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002144 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002145 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002146 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002147 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002148 }
Chris Ye989bb932020-07-04 16:18:59 -07002149 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002150 createVirtualKeyboardLocked();
2151 }
2152}
2153
2154// ----------------------------------------------------------------------------
2155
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002156status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002157 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002158 struct epoll_event eventItem = {};
2159 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2160 eventItem.data.fd = fd;
2161 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2162 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002163 return -errno;
2164 }
2165 return OK;
2166}
2167
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002168status_t EventHub::unregisterFdFromEpoll(int fd) {
2169 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2170 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2171 return -errno;
2172 }
2173 return OK;
2174}
2175
Chris Ye989bb932020-07-04 16:18:59 -07002176status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2177 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002178 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002179 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002180 return result;
2181 }
Chris Ye989bb932020-07-04 16:18:59 -07002182 if (device.videoDevice) {
2183 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002184 }
2185 return result;
2186}
2187
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002188void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2189 status_t result = registerFdForEpoll(videoDevice.getFd());
2190 if (result != OK) {
2191 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2192 }
2193}
2194
Chris Ye989bb932020-07-04 16:18:59 -07002195status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2196 if (device.hasValidFd()) {
2197 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002198 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002199 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002200 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002201 }
2202 }
Chris Ye989bb932020-07-04 16:18:59 -07002203 if (device.videoDevice) {
2204 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002205 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002206 return OK;
2207}
2208
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002209void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2210 if (videoDevice.hasValidFd()) {
2211 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2212 if (result != OK) {
2213 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002214 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002215 }
2216 }
2217}
2218
Chris Yed3fef462021-03-07 17:10:08 -08002219void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002220 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002221 SHA256_CTX ctx;
2222 SHA256_Init(&ctx);
2223 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2224 identifier.uniqueId.size());
2225 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2226 SHA256_Final(digest.data(), &ctx);
2227
2228 std::string obfuscatedId;
2229 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2230 obfuscatedId += StringPrintf("%02x", digest[i]);
2231 }
2232
Chris Yed3fef462021-03-07 17:10:08 -08002233 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2234 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002235 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002236}
2237
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002238void EventHub::openDeviceLocked(const std::string& devicePath) {
2239 // If an input device happens to register around the time when EventHub's constructor runs, it
2240 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2241 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2242 // from getting registered, ensure that this path is not already covered by an existing device.
2243 for (const auto& [deviceId, device] : mDevices) {
2244 if (device->path == devicePath) {
2245 return; // device was already registered
2246 }
2247 }
2248
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 char buffer[80];
2250
Chris Ye8594e192020-07-14 10:34:06 -07002251 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
Chris Ye8594e192020-07-14 10:34:06 -07002253 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002254 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002255 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002256 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
2258
2259 InputDeviceIdentifier identifier;
2260
2261 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002262 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002263 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 } else {
2265 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002266 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 }
2268
2269 // Check to see if the device is on our excluded list
2270 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002271 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002272 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002273 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002275 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277 }
2278
2279 // Get device driver version.
2280 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002281 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002282 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002284 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 }
2286
2287 // Get device identifier.
2288 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002289 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002290 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002292 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294 identifier.bus = inputId.bustype;
2295 identifier.product = inputId.product;
2296 identifier.vendor = inputId.vendor;
2297 identifier.version = inputId.version;
2298
2299 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002300 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2301 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302 } else {
2303 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002304 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306
2307 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002308 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2309 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 } else {
2311 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002312 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002313 }
2314
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002315 // Attempt to get the bluetooth address of an input device from the uniqueId.
2316 if (identifier.bus == BUS_BLUETOOTH &&
2317 std::regex_match(identifier.uniqueId,
2318 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2319 identifier.bluetoothAddress = identifier.uniqueId;
2320 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2321 for (auto& c : *identifier.bluetoothAddress) {
2322 c = ::toupper(c);
2323 }
2324 }
2325
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326 // Fill in the descriptor.
2327 assignDescriptorLocked(identifier);
2328
Michael Wrightd02c5b62014-02-10 15:10:22 -08002329 // Allocate device. (The device object takes ownership of the fd at this point.)
2330 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002331 std::unique_ptr<Device> device =
2332 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2333 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334
Chris Ye8594e192020-07-14 10:34:06 -07002335 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002337 " vendor %04x\n"
2338 " product %04x\n"
2339 " version %04x\n",
2340 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002341 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2342 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2343 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2344 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002345 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2346 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347
2348 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002349 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002350
2351 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002352 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2353 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2354 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2355 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2356 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2357 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002358 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002359 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002360
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002361 // See if this is a device with keys. This could be full keyboard, or other devices like
2362 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002363 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002364 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2365 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2366 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002367 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2368 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2369 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002370 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 }
2372
2373 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002374 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2375 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002376 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002377 }
2378
Prabir Pradhana3621852022-10-14 18:57:23 +00002379 // See if the device is specially configured to be of a certain type.
Harry Cuttsf13161a2023-03-08 14:15:49 +00002380 if (device->configuration) {
2381 std::string deviceType = device->configuration->getString("device.type").value_or("");
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002382 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002383 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002384 } else if (deviceType == "externalStylus") {
2385 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002386 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002387 }
2388
Michael Wrightd02c5b62014-02-10 15:10:22 -08002389 // See if this is a touch pad.
2390 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002391 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392 // Some joysticks such as the PS3 controller report axes that conflict
2393 // with the ABS_MT range. Try to confirm that the device really is
2394 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002395 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002396 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002397 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2398 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2399 device->classes |= InputDeviceClass::TOUCHPAD;
2400 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002401 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002402 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002403 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2404 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002405 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002406 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002407 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2408 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002409 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411
2412 // See if this device is a joystick.
2413 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2414 // from other devices such as accelerometers that also have absolute axes.
2415 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002416 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002418 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002419 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 device->classes = assumedClasses;
2421 break;
2422 }
2423 }
2424 }
2425
Chris Yef59a2f42020-10-16 12:55:26 -07002426 // Check whether this device is an accelerometer.
2427 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2428 device->classes |= InputDeviceClass::SENSOR;
2429 }
2430
Michael Wrightd02c5b62014-02-10 15:10:22 -08002431 // Check whether this device has switches.
2432 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002433 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002434 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002435 break;
2436 }
2437 }
2438
2439 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002440 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002441 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443
2444 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002445 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 // Load the virtual keys for the touch screen, if any.
2447 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002448 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002449 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002450 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002451 }
2452 }
2453
2454 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002455 // We need to do this for joysticks too because the key layout may specify axes, and for
2456 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002458 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2459 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002461 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002462 }
2463
2464 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002465 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002466 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002467 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002468 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2469 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002470 mBuiltInKeyboardId = device->id;
2471 }
2472
2473 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002474 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002475 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002476 }
2477
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002478 // See if this device has a D-pad.
2479 if (std::all_of(DPAD_REQUIRED_KEYCODES.begin(), DPAD_REQUIRED_KEYCODES.end(),
2480 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002481 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002482 }
2483
2484 // See if this device has a gamepad.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002485 if (std::any_of(GAMEPAD_KEYCODES.begin(), GAMEPAD_KEYCODES.end(),
2486 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2487 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002488 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002489
2490 // See if this device has any stylus buttons that we would want to fuse with touch data.
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002491 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT) &&
Prabir Pradhan3c28b942023-08-18 20:02:01 +00002492 !device->classes.any(InputDeviceClass::ALPHAKEY) &&
Prabir Pradhanae10ee62023-05-12 19:44:18 +00002493 std::any_of(STYLUS_BUTTON_KEYCODES.begin(), STYLUS_BUTTON_KEYCODES.end(),
2494 [&](int32_t keycode) { return device->hasKeycodeLocked(keycode); })) {
2495 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhana3621852022-10-14 18:57:23 +00002496 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002497 }
2498
2499 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002500 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002501 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002502 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002503 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002504 }
2505
Chris Ye3fdbfef2021-01-06 18:45:18 -08002506 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002507 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002508 device->classes |= InputDeviceClass::BATTERY;
2509 }
Kim Low03ea0352020-11-06 12:45:07 -08002510
Chris Ye3fdbfef2021-01-06 18:45:18 -08002511 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002512 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002513 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002514 }
2515
Tim Kilbourn063ff532015-04-08 10:26:18 -07002516 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002517 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002518 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002519 }
2520
Michael Wrightd02c5b62014-02-10 15:10:22 -08002521 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002522 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002523 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002524 }
2525
Chris Ye1b0c7342020-07-28 21:57:03 -07002526 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2527 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002528 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2529 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002530 }
2531
Chris Ye989bb932020-07-04 16:18:59 -07002532 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002533 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 }
2535
Chris Ye989bb932020-07-04 16:18:59 -07002536 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002537
Chris Ye1b0c7342020-07-28 21:57:03 -07002538 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002539 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002540 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2541 device->classes.string().c_str(), device->configurationFile.c_str(),
2542 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2543 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002544
Chris Ye989bb932020-07-04 16:18:59 -07002545 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002546}
2547
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002548void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2549 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2550 if (!videoDevice) {
2551 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2552 return;
2553 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002554 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002555 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002556 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002557 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002558 }
2559 }
2560
2561 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2562 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002563 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002564 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002565 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2566}
2567
Chris Yed3fef462021-03-07 17:10:08 -08002568bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2569 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002570 if (videoDevice->getName() != device.identifier.name) {
2571 return false;
2572 }
2573 device.videoDevice = std::move(videoDevice);
2574 if (device.enabled) {
2575 registerVideoDeviceForEpollLocked(*device.videoDevice);
2576 }
2577 return true;
2578}
2579
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002580bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002581 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002582 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002583 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002584 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2585 return false;
2586 }
2587 return device->enabled;
2588}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002590status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002591 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002592 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002593 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002594 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2595 return BAD_VALUE;
2596 }
2597 if (device->enabled) {
2598 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2599 return OK;
2600 }
2601 status_t result = device->enable();
2602 if (result != OK) {
2603 ALOGE("Failed to enable device %" PRId32, deviceId);
2604 return result;
2605 }
2606
Chris Ye989bb932020-07-04 16:18:59 -07002607 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002608
Chris Ye989bb932020-07-04 16:18:59 -07002609 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002610}
2611
2612status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002613 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002614 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002615 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002616 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2617 return BAD_VALUE;
2618 }
2619 if (!device->enabled) {
2620 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2621 return OK;
2622 }
Chris Ye989bb932020-07-04 16:18:59 -07002623 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002624 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625}
2626
Vaibhav Devmurari5fc7d852023-03-17 18:43:33 +00002627// TODO(b/274755573): Shift to uevent handling on native side and remove this method
2628// Currently using Java UEventObserver to trigger this which uses UEvent infrastructure that uses a
2629// NETLINK socket to observe UEvents. We can create similar infrastructure on Eventhub side to
2630// directly observe UEvents instead of triggering from Java side.
2631void EventHub::sysfsNodeChanged(const std::string& sysfsNodePath) {
2632 std::scoped_lock _l(mLock);
2633
2634 // Check in opening devices
2635 for (auto it = mOpeningDevices.begin(); it != mOpeningDevices.end(); it++) {
2636 std::unique_ptr<Device>& device = *it;
2637 if (device->associatedDevice &&
2638 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2639 std::string::npos &&
2640 device->associatedDevice->isChanged()) {
2641 it = mOpeningDevices.erase(it);
2642 openDeviceLocked(device->path);
2643 }
2644 }
2645
2646 // Check in already added device
2647 std::vector<Device*> devicesToReopen;
2648 for (const auto& [id, device] : mDevices) {
2649 if (device->associatedDevice &&
2650 sysfsNodePath.find(device->associatedDevice->sysfsRootPath.string()) !=
2651 std::string::npos &&
2652 device->associatedDevice->isChanged()) {
2653 devicesToReopen.push_back(device.get());
2654 }
2655 }
2656 for (const auto& device : devicesToReopen) {
2657 closeDeviceLocked(*device);
2658 openDeviceLocked(device->path);
2659 }
2660 devicesToReopen.clear();
2661}
2662
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663void EventHub::createVirtualKeyboardLocked() {
2664 InputDeviceIdentifier identifier;
2665 identifier.name = "Virtual";
2666 identifier.uniqueId = "<virtual>";
2667 assignDescriptorLocked(identifier);
2668
Chris Ye989bb932020-07-04 16:18:59 -07002669 std::unique_ptr<Device> device =
2670 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002671 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002672 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2673 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002674 device->loadKeyMapLocked();
2675 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002676}
2677
Chris Ye989bb932020-07-04 16:18:59 -07002678void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002679 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002680 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681}
2682
Chris Ye989bb932020-07-04 16:18:59 -07002683int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002684 if (mControllerNumbers.isFull()) {
2685 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002686 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 return 0;
2688 }
2689 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2690 // one
2691 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2692}
2693
Chris Ye989bb932020-07-04 16:18:59 -07002694void EventHub::releaseControllerNumberLocked(int32_t num) {
2695 if (num > 0) {
2696 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002697 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698}
2699
Chris Ye8594e192020-07-14 10:34:06 -07002700void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002702 if (device != nullptr) {
2703 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002704 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002705 }
Chris Ye8594e192020-07-14 10:34:06 -07002706 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002707}
2708
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002709/**
2710 * Find the video device by filename, and close it.
2711 * The video device is closed by path during an inotify event, where we don't have the
2712 * additional context about the video device fd, or the associated input device.
2713 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002714void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002715 // A video device may be owned by an existing input device, or it may be stored in
2716 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002717 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002718 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002719 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002720 device->videoDevice = nullptr;
2721 return;
2722 }
2723 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002724 std::erase_if(mUnattachedVideoDevices,
2725 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2726 return videoDevice->getPath() == devicePath;
2727 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728}
2729
2730void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002731 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002732 while (!mDevices.empty()) {
2733 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 }
2735}
2736
Chris Ye989bb932020-07-04 16:18:59 -07002737void EventHub::closeDeviceLocked(Device& device) {
2738 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2739 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740
Chris Ye989bb932020-07-04 16:18:59 -07002741 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002743 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002744 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2745 }
2746
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002747 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002748 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002749 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002750 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002751 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752
Chris Ye989bb932020-07-04 16:18:59 -07002753 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002754 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002755 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002756 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002757
Chris Ye989bb932020-07-04 16:18:59 -07002758 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002759}
2760
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002761base::Result<void> EventHub::readNotifyLocked() {
2762 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2763 uint8_t eventBuffer[512];
2764 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
2766 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002767 do {
2768 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2769 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002771 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2772
2773 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2774 const inotify_event* event;
2775 event = (const inotify_event*)(eventBuffer + eventPos);
2776 if (event->len == 0) continue;
2777
2778 handleNotifyEventLocked(*event);
2779
2780 const ssize_t eventSize = EVENT_SIZE + event->len;
2781 sizeRead -= eventSize;
2782 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002783 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002784 return {};
2785}
2786
2787void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2788 if (event.wd == mDeviceInputWd) {
2789 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2790 if (event.mask & IN_CREATE) {
2791 openDeviceLocked(filename);
2792 } else {
2793 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2794 closeDeviceByPathLocked(filename);
2795 }
2796 } else if (event.wd == mDeviceWd) {
2797 if (isV4lTouchNode(event.name)) {
2798 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2799 if (event.mask & IN_CREATE) {
2800 openVideoDeviceLocked(filename);
2801 } else {
2802 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2803 closeVideoDeviceByPathLocked(filename);
2804 }
2805 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2806 addDeviceInputInotify();
2807 }
2808 } else {
2809 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2810 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002811}
2812
Chris Ye8594e192020-07-14 10:34:06 -07002813status_t EventHub::scanDirLocked(const std::string& dirname) {
2814 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2815 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 return 0;
2818}
2819
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002820/**
2821 * Look for all dirname/v4l-touch* devices, and open them.
2822 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002823status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002824 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2825 if (isV4lTouchNode(entry.path())) {
2826 ALOGI("Found touch video device %s", entry.path().c_str());
2827 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002828 }
2829 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002830 return OK;
2831}
2832
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833void EventHub::requestReopenDevices() {
2834 ALOGV("requestReopenDevices() called");
2835
Chris Ye87143712020-11-10 05:05:58 +00002836 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 mNeedToReopenDevices = true;
2838}
2839
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002840void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002841 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842
2843 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002844 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002846 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002848 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002849
Chris Ye989bb932020-07-04 16:18:59 -07002850 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002852 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002853 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002855 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002856 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002857 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002858 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002859 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002860 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002861 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2862 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002863 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002864 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002865 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002866 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002867 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002868 device->identifier.product, device->identifier.version,
2869 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002870 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002871 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002872 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002873 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002874 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2875 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2876 device->associatedDevice->layoutInfo->languageTag.c_str());
2877 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2878 device->associatedDevice->layoutInfo->layoutType.c_str());
2879 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002880 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002881 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002882 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2883 device->videoDevice ? device->videoDevice->dump().c_str()
2884 : "<none>");
2885 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2886 device->associatedDevice
2887 ? device->associatedDevice->sysfsRootPath.c_str()
2888 : "<none>");
Prabir Pradhan955b6132023-07-14 19:44:34 +00002889 if (device->keyBitmask.any(0, KEY_MAX + 1)) {
2890 const auto pressedKeys = device->keyState.dumpSetIndices(", ", [](int i) {
2891 return InputEventLookup::getLinuxEvdevLabel(EV_KEY, i, 1).code;
2892 });
2893 dump += StringPrintf(INDENT3 "KeyState (pressed): %s\n", pressedKeys.c_str());
2894 }
2895 if (device->swBitmask.any(0, SW_MAX + 1)) {
2896 const auto pressedSwitches = device->swState.dumpSetIndices(", ", [](int i) {
2897 return InputEventLookup::getLinuxEvdevLabel(EV_SW, i, 1).code;
2898 });
2899 dump += StringPrintf(INDENT3 "SwState (pressed): %s\n", pressedSwitches.c_str());
2900 }
2901 if (!device->absState.empty()) {
2902 std::string axisValues;
2903 for (const auto& [axis, state] : device->absState) {
2904 if (!axisValues.empty()) {
2905 axisValues += ", ";
2906 }
2907 axisValues += StringPrintf("%s=%d",
2908 InputEventLookup::getLinuxEvdevLabel(EV_ABS, axis, 0)
2909 .code.c_str(),
2910 state.value);
2911 }
2912 dump += INDENT3 "AbsState: " + axisValues + "\n";
2913 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002915
2916 dump += INDENT "Unattached video devices:\n";
2917 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2918 dump += INDENT2 + videoDevice->dump() + "\n";
2919 }
2920 if (mUnattachedVideoDevices.empty()) {
2921 dump += INDENT2 "<none>\n";
2922 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 } // release lock
2924}
2925
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002926void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002928 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002929}
2930
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002931std::string EventHub::AssociatedDevice::dump() const {
2932 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2933 batteryInfos.size(), lightInfos.size());
2934}
2935
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002936} // namespace android