blob: d3d80216450929463a3a8b0a32a4d336d1f67d5d [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2005 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070017#include <assert.h>
18#include <dirent.h>
19#include <errno.h>
20#include <fcntl.h>
21#include <inttypes.h>
Colin Cross5b799302022-10-18 21:52:41 -070022#include <linux/ioctl.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070023#include <memory.h>
24#include <stdint.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +010028#include <sys/capability.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070029#include <sys/epoll.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070030#include <sys/inotify.h>
31#include <sys/ioctl.h>
Kim Low03ea0352020-11-06 12:45:07 -080032#include <sys/stat.h>
33#include <sys/sysmacros.h>
Mark Salyzyn5aa26b22014-06-10 13:07:44 -070034#include <unistd.h>
35
Michael Wrightd02c5b62014-02-10 15:10:22 -080036#define LOG_TAG "EventHub"
37
38// #define LOG_NDEBUG 0
Kim Low03ea0352020-11-06 12:45:07 -080039#include <android-base/file.h>
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080040#include <android-base/stringprintf.h>
Chris Yed3fef462021-03-07 17:10:08 -080041#include <android-base/strings.h>
Philip Quinn39b81682019-01-09 22:20:39 -080042#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080043#include <ftl/enum.h>
Chris Ye8594e192020-07-14 10:34:06 -070044#include <input/KeyCharacterMap.h>
45#include <input/KeyLayoutMap.h>
Prabir Pradhan07525ef2022-10-03 21:51:26 +000046#include <input/PrintTools.h>
Chris Ye8594e192020-07-14 10:34:06 -070047#include <input/VirtualKeyMap.h>
Dan Albert677d87e2014-06-16 17:31:28 -070048#include <openssl/sha.h>
Chris Yed3fef462021-03-07 17:10:08 -080049#include <statslog.h>
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070050#include <utils/Errors.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <utils/Log.h>
52#include <utils/Timers.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080053
Chris Ye8594e192020-07-14 10:34:06 -070054#include <filesystem>
Chris Ye3fdbfef2021-01-06 18:45:18 -080055#include <regex>
Prabir Pradhancb42b472022-08-23 16:01:19 +000056#include <utility>
Chris Ye8594e192020-07-14 10:34:06 -070057
58#include "EventHub.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080059
Michael Wrightd02c5b62014-02-10 15:10:22 -080060#define INDENT " "
61#define INDENT2 " "
62#define INDENT3 " "
63
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080064using android::base::StringPrintf;
65
Michael Wrightd02c5b62014-02-10 15:10:22 -080066namespace android {
67
Dominik Laskowski2f01d772022-03-23 16:01:29 -070068using namespace ftl::flag_operators;
69
Usama Arifb27c8e62021-06-03 16:44:09 +010070static const char* DEVICE_INPUT_PATH = "/dev/input";
Siarhei Vishniakou951f3622018-12-12 19:45:42 -080071// v4l2 devices go directly into /dev
Usama Arifb27c8e62021-06-03 16:44:09 +010072static const char* DEVICE_PATH = "/dev";
Michael Wrightd02c5b62014-02-10 15:10:22 -080073
Chris Ye657c2f02021-05-25 16:24:37 -070074static constexpr size_t OBFUSCATED_LENGTH = 8;
75
Chris Ye87143712020-11-10 05:05:58 +000076static constexpr int32_t FF_STRONG_MAGNITUDE_CHANNEL_IDX = 0;
77static constexpr int32_t FF_WEAK_MAGNITUDE_CHANNEL_IDX = 1;
Chris Ye6393a262020-08-04 19:41:36 -070078
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -070079static constexpr size_t EVENT_BUFFER_SIZE = 256;
80
Chris Yee2b1e5c2021-03-10 22:45:12 -080081// Mapping for input battery class node IDs lookup.
82// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
83static const std::unordered_map<std::string, InputBatteryClass> BATTERY_CLASSES =
84 {{"capacity", InputBatteryClass::CAPACITY},
85 {"capacity_level", InputBatteryClass::CAPACITY_LEVEL},
86 {"status", InputBatteryClass::STATUS}};
87
88// Mapping for input battery class node names lookup.
89// https://www.kernel.org/doc/Documentation/power/power_supply_class.txt
90static const std::unordered_map<InputBatteryClass, std::string> BATTERY_NODES =
91 {{InputBatteryClass::CAPACITY, "capacity"},
92 {InputBatteryClass::CAPACITY_LEVEL, "capacity_level"},
93 {InputBatteryClass::STATUS, "status"}};
94
Kim Low03ea0352020-11-06 12:45:07 -080095// must be kept in sync with definitions in kernel /drivers/power/supply/power_supply_sysfs.c
96static const std::unordered_map<std::string, int32_t> BATTERY_STATUS =
97 {{"Unknown", BATTERY_STATUS_UNKNOWN},
98 {"Charging", BATTERY_STATUS_CHARGING},
99 {"Discharging", BATTERY_STATUS_DISCHARGING},
100 {"Not charging", BATTERY_STATUS_NOT_CHARGING},
101 {"Full", BATTERY_STATUS_FULL}};
102
103// Mapping taken from
104// https://gitlab.freedesktop.org/upower/upower/-/blob/master/src/linux/up-device-supply.c#L484
105static const std::unordered_map<std::string, int32_t> BATTERY_LEVEL = {{"Critical", 5},
106 {"Low", 10},
107 {"Normal", 55},
108 {"High", 70},
109 {"Full", 100},
110 {"Unknown", 50}};
111
Chris Ye3fdbfef2021-01-06 18:45:18 -0800112// Mapping for input led class node names lookup.
113// https://www.kernel.org/doc/html/latest/leds/leds-class.html
114static const std::unordered_map<std::string, InputLightClass> LIGHT_CLASSES =
115 {{"red", InputLightClass::RED},
116 {"green", InputLightClass::GREEN},
117 {"blue", InputLightClass::BLUE},
118 {"global", InputLightClass::GLOBAL},
119 {"brightness", InputLightClass::BRIGHTNESS},
120 {"multi_index", InputLightClass::MULTI_INDEX},
121 {"multi_intensity", InputLightClass::MULTI_INTENSITY},
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000122 {"max_brightness", InputLightClass::MAX_BRIGHTNESS},
123 {"kbd_backlight", InputLightClass::KEYBOARD_BACKLIGHT}};
Chris Ye3fdbfef2021-01-06 18:45:18 -0800124
125// Mapping for input multicolor led class node names.
126// https://www.kernel.org/doc/html/latest/leds/leds-class-multicolor.html
127static const std::unordered_map<InputLightClass, std::string> LIGHT_NODES =
128 {{InputLightClass::BRIGHTNESS, "brightness"},
129 {InputLightClass::MULTI_INDEX, "multi_index"},
130 {InputLightClass::MULTI_INTENSITY, "multi_intensity"}};
131
132// Mapping for light color name and the light color
133const std::unordered_map<std::string, LightColor> LIGHT_COLORS = {{"red", LightColor::RED},
134 {"green", LightColor::GREEN},
135 {"blue", LightColor::BLUE}};
136
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000137// Mapping for country code to Layout info.
138// See bCountryCode in 6.2.1 of https://usb.org/sites/default/files/hid1_11.pdf.
139const std::unordered_map<std::int32_t, RawLayoutInfo> LAYOUT_INFOS =
140 {{0, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // NOT_SUPPORTED
141 {1, RawLayoutInfo{.languageTag = "ar-Arab", .layoutType = ""}}, // ARABIC
142 {2, RawLayoutInfo{.languageTag = "fr-BE", .layoutType = ""}}, // BELGIAN
143 {3, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_BILINGUAL
144 {4, RawLayoutInfo{.languageTag = "fr-CA", .layoutType = ""}}, // CANADIAN_FRENCH
145 {5, RawLayoutInfo{.languageTag = "cs", .layoutType = ""}}, // CZECH_REPUBLIC
146 {6, RawLayoutInfo{.languageTag = "da", .layoutType = ""}}, // DANISH
147 {7, RawLayoutInfo{.languageTag = "fi", .layoutType = ""}}, // FINNISH
148 {8, RawLayoutInfo{.languageTag = "fr-FR", .layoutType = ""}}, // FRENCH
149 {9, RawLayoutInfo{.languageTag = "de", .layoutType = ""}}, // GERMAN
150 {10, RawLayoutInfo{.languageTag = "el", .layoutType = ""}}, // GREEK
151 {11, RawLayoutInfo{.languageTag = "iw", .layoutType = ""}}, // HEBREW
152 {12, RawLayoutInfo{.languageTag = "hu", .layoutType = ""}}, // HUNGARY
153 {13, RawLayoutInfo{.languageTag = "en", .layoutType = "extended"}}, // INTERNATIONAL (ISO)
154 {14, RawLayoutInfo{.languageTag = "it", .layoutType = ""}}, // ITALIAN
155 {15, RawLayoutInfo{.languageTag = "ja", .layoutType = ""}}, // JAPAN
156 {16, RawLayoutInfo{.languageTag = "ko", .layoutType = ""}}, // KOREAN
157 {17, RawLayoutInfo{.languageTag = "es-419", .layoutType = ""}}, // LATIN_AMERICA
158 {18, RawLayoutInfo{.languageTag = "nl", .layoutType = ""}}, // DUTCH
159 {19, RawLayoutInfo{.languageTag = "nb", .layoutType = ""}}, // NORWEGIAN
160 {20, RawLayoutInfo{.languageTag = "fa", .layoutType = ""}}, // PERSIAN
161 {21, RawLayoutInfo{.languageTag = "pl", .layoutType = ""}}, // POLAND
162 {22, RawLayoutInfo{.languageTag = "pt", .layoutType = ""}}, // PORTUGUESE
163 {23, RawLayoutInfo{.languageTag = "ru", .layoutType = ""}}, // RUSSIA
164 {24, RawLayoutInfo{.languageTag = "sk", .layoutType = ""}}, // SLOVAKIA
165 {25, RawLayoutInfo{.languageTag = "es-ES", .layoutType = ""}}, // SPANISH
166 {26, RawLayoutInfo{.languageTag = "sv", .layoutType = ""}}, // SWEDISH
167 {27, RawLayoutInfo{.languageTag = "fr-CH", .layoutType = ""}}, // SWISS_FRENCH
168 {28, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWISS_GERMAN
169 {29, RawLayoutInfo{.languageTag = "de-CH", .layoutType = ""}}, // SWITZERLAND
170 {30, RawLayoutInfo{.languageTag = "zh-TW", .layoutType = ""}}, // TAIWAN
171 {31, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_q"}}, // TURKISH_Q
172 {32, RawLayoutInfo{.languageTag = "en-GB", .layoutType = ""}}, // UK
173 {33, RawLayoutInfo{.languageTag = "en-US", .layoutType = ""}}, // US
174 {34, RawLayoutInfo{.languageTag = "", .layoutType = ""}}, // YUGOSLAVIA
175 {35, RawLayoutInfo{.languageTag = "tr", .layoutType = "turkish_f"}}}; // TURKISH_F
176
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100177static std::string sha1(const std::string& in) {
Dan Albert677d87e2014-06-16 17:31:28 -0700178 SHA_CTX ctx;
179 SHA1_Init(&ctx);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100180 SHA1_Update(&ctx, reinterpret_cast<const u_char*>(in.c_str()), in.size());
Dan Albert677d87e2014-06-16 17:31:28 -0700181 u_char digest[SHA_DIGEST_LENGTH];
182 SHA1_Final(digest, &ctx);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800183
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100184 std::string out;
Dan Albert677d87e2014-06-16 17:31:28 -0700185 for (size_t i = 0; i < SHA_DIGEST_LENGTH; i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100186 out += StringPrintf("%02x", digest[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800187 }
188 return out;
189}
190
Prabir Pradhana3621852022-10-14 18:57:23 +0000191/* The set of all Android key codes that correspond to buttons (bit-switches) on a stylus. */
192static constexpr std::array<int32_t, 4> STYLUS_BUTTON_KEYCODES = {
193 AKEYCODE_STYLUS_BUTTON_PRIMARY,
194 AKEYCODE_STYLUS_BUTTON_SECONDARY,
195 AKEYCODE_STYLUS_BUTTON_TERTIARY,
196 AKEYCODE_STYLUS_BUTTON_TAIL,
197};
198
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800199/**
200 * Return true if name matches "v4l-touch*"
201 */
Chris Ye8594e192020-07-14 10:34:06 -0700202static bool isV4lTouchNode(std::string name) {
203 return name.find("v4l-touch") != std::string::npos;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800204}
205
Philip Quinn39b81682019-01-09 22:20:39 -0800206/**
207 * Returns true if V4L devices should be scanned.
208 *
209 * The system property ro.input.video_enabled can be used to control whether
210 * EventHub scans and opens V4L devices. As V4L does not support multiple
211 * clients, EventHub effectively blocks access to these devices when it opens
Siarhei Vishniakou29f88492019-04-05 14:11:43 -0700212 * them.
213 *
214 * Setting this to "false" would prevent any video devices from being discovered and
215 * associated with input devices.
216 *
217 * This property can be used as follows:
218 * 1. To turn off features that are dependent on video device presence.
219 * 2. During testing and development, to allow other clients to read video devices
220 * directly from /dev.
Philip Quinn39b81682019-01-09 22:20:39 -0800221 */
222static bool isV4lScanningEnabled() {
Harry Cutts33476232023-01-30 19:57:29 +0000223 return property_get_bool("ro.input.video_enabled", /*default_value=*/true);
Philip Quinn39b81682019-01-09 22:20:39 -0800224}
225
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800226static nsecs_t processEventTimestamp(const struct input_event& event) {
227 // Use the time specified in the event instead of the current time
228 // so that downstream code can get more accurate estimates of
229 // event dispatch latency from the time the event is enqueued onto
230 // the evdev client buffer.
231 //
232 // The event's timestamp fortuitously uses the same monotonic clock
233 // time base as the rest of Android. The kernel event device driver
234 // (drivers/input/evdev.c) obtains timestamps using ktime_get_ts().
235 // The systemTime(SYSTEM_TIME_MONOTONIC) function we use everywhere
236 // calls clock_gettime(CLOCK_MONOTONIC) which is implemented as a
237 // system call that also queries ktime_get_ts().
238
Colin Cross5b799302022-10-18 21:52:41 -0700239 const nsecs_t inputEventTime = seconds_to_nanoseconds(event.input_event_sec) +
240 microseconds_to_nanoseconds(event.input_event_usec);
Siarhei Vishniakou592bac22018-11-08 19:42:38 -0800241 return inputEventTime;
242}
243
Kim Low03ea0352020-11-06 12:45:07 -0800244/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000245 * Returns the sysfs root path of the input device.
Kim Low03ea0352020-11-06 12:45:07 -0800246 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800247static std::optional<std::filesystem::path> getSysfsRootPath(const char* devicePath) {
Kim Low03ea0352020-11-06 12:45:07 -0800248 std::error_code errorCode;
249
250 // Stat the device path to get the major and minor number of the character file
251 struct stat statbuf;
252 if (stat(devicePath, &statbuf) == -1) {
253 ALOGE("Could not stat device %s due to error: %s.", devicePath, std::strerror(errno));
Chris Ye3fdbfef2021-01-06 18:45:18 -0800254 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800255 }
256
257 unsigned int major_num = major(statbuf.st_rdev);
258 unsigned int minor_num = minor(statbuf.st_rdev);
259
260 // Realpath "/sys/dev/char/{major}:{minor}" to get the sysfs path to the input event
261 auto sysfsPath = std::filesystem::path("/sys/dev/char/");
262 sysfsPath /= std::to_string(major_num) + ":" + std::to_string(minor_num);
263 sysfsPath = std::filesystem::canonical(sysfsPath, errorCode);
264
265 // Make sure nothing went wrong in call to canonical()
266 if (errorCode) {
267 ALOGW("Could not run filesystem::canonical() due to error %d : %s.", errorCode.value(),
268 errorCode.message().c_str());
Chris Ye3fdbfef2021-01-06 18:45:18 -0800269 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800270 }
271
272 // Continue to go up a directory until we reach a directory named "input"
273 while (sysfsPath != "/" && sysfsPath.filename() != "input") {
274 sysfsPath = sysfsPath.parent_path();
275 }
276
277 // Then go up one more and you will be at the sysfs root of the device
278 sysfsPath = sysfsPath.parent_path();
279
280 // Make sure we didn't reach root path and that directory actually exists
281 if (sysfsPath == "/" || !std::filesystem::exists(sysfsPath, errorCode)) {
282 if (errorCode) {
283 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
284 errorCode.message().c_str());
285 }
286
287 // Not found
Chris Ye3fdbfef2021-01-06 18:45:18 -0800288 return std::nullopt;
Kim Low03ea0352020-11-06 12:45:07 -0800289 }
290
291 return sysfsPath;
292}
293
294/**
Chris Ye3fdbfef2021-01-06 18:45:18 -0800295 * Returns the list of files under a specified path.
Kim Low03ea0352020-11-06 12:45:07 -0800296 */
Chris Ye3fdbfef2021-01-06 18:45:18 -0800297static std::vector<std::filesystem::path> allFilesInPath(const std::filesystem::path& path) {
298 std::vector<std::filesystem::path> nodes;
299 std::error_code errorCode;
300 auto iter = std::filesystem::directory_iterator(path, errorCode);
301 while (!errorCode && iter != std::filesystem::directory_iterator()) {
302 nodes.push_back(iter->path());
303 iter++;
304 }
305 return nodes;
306}
307
308/**
309 * Returns the list of files under a specified directory in a sysfs path.
310 * Example:
311 * findSysfsNodes(sysfsRootPath, SysfsClass::LEDS) will return all led nodes under "leds" directory
312 * in the sysfs path.
313 */
314static std::vector<std::filesystem::path> findSysfsNodes(const std::filesystem::path& sysfsRoot,
315 SysfsClass clazz) {
Dominik Laskowski75788452021-02-09 18:51:25 -0800316 std::string nodeStr = ftl::enum_string(clazz);
Chris Ye3fdbfef2021-01-06 18:45:18 -0800317 std::for_each(nodeStr.begin(), nodeStr.end(),
318 [](char& c) { c = std::tolower(static_cast<unsigned char>(c)); });
319 std::vector<std::filesystem::path> nodes;
320 for (auto path = sysfsRoot; path != "/" && nodes.empty(); path = path.parent_path()) {
321 nodes = allFilesInPath(path / nodeStr);
322 }
323 return nodes;
324}
325
326static std::optional<std::array<LightColor, COLOR_NUM>> getColorIndexArray(
327 std::filesystem::path path) {
328 std::string indexStr;
329 if (!base::ReadFileToString(path, &indexStr)) {
330 return std::nullopt;
331 }
332
333 // Parse the multi color LED index file, refer to kernel docs
334 // leds/leds-class-multicolor.html
335 std::regex indexPattern("(red|green|blue)\\s(red|green|blue)\\s(red|green|blue)[\\n]");
336 std::smatch results;
337 std::array<LightColor, COLOR_NUM> colors;
338 if (!std::regex_match(indexStr, results, indexPattern)) {
339 return std::nullopt;
340 }
341
342 for (size_t i = 1; i < results.size(); i++) {
343 const auto it = LIGHT_COLORS.find(results[i].str());
344 if (it != LIGHT_COLORS.end()) {
345 // intensities.emplace(it->second, 0);
346 colors[i - 1] = it->second;
Kim Low03ea0352020-11-06 12:45:07 -0800347 }
348 }
Chris Ye3fdbfef2021-01-06 18:45:18 -0800349 return colors;
Kim Low03ea0352020-11-06 12:45:07 -0800350}
351
Prabir Pradhancb42b472022-08-23 16:01:19 +0000352/**
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000353 * Read country code information exposed through the sysfs path and convert it to Layout info.
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000354 */
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000355static std::optional<RawLayoutInfo> readLayoutConfiguration(
356 const std::filesystem::path& sysfsRootPath) {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000357 // Check the sysfs root path
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000358 int32_t hidCountryCode = -1;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000359 std::string str;
360 if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
361 hidCountryCode = std::stoi(str, nullptr, 16);
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000362 // Update this condition if new supported country codes are added to HID spec.
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000363 if (hidCountryCode > 35 || hidCountryCode < 0) {
364 ALOGE("HID country code should be in range [0, 35], but for sysfs path %s it was %d",
365 sysfsRootPath.c_str(), hidCountryCode);
Vaibhav Devmurari990ff7b2022-12-22 18:23:21 +0000366 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000367 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000368 const auto it = LAYOUT_INFOS.find(hidCountryCode);
369 if (it != LAYOUT_INFOS.end()) {
370 return it->second;
371 }
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000372
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +0000373 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +0000374}
375
376/**
Prabir Pradhancb42b472022-08-23 16:01:19 +0000377 * Read information about batteries exposed through the sysfs path.
378 */
379static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
380 const std::filesystem::path& sysfsRootPath) {
381 std::unordered_map<int32_t, RawBatteryInfo> batteryInfos;
382 int32_t nextBatteryId = 0;
383 // Check if device has any battery.
384 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::POWER_SUPPLY);
385 for (const auto& nodePath : paths) {
386 RawBatteryInfo info;
387 info.id = ++nextBatteryId;
388 info.path = nodePath;
389 info.name = nodePath.filename();
390
391 // Scan the path for all the files
392 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
393 const auto& files = allFilesInPath(nodePath);
394 for (const auto& file : files) {
395 const auto it = BATTERY_CLASSES.find(file.filename().string());
396 if (it != BATTERY_CLASSES.end()) {
397 info.flags |= it->second;
398 }
399 }
400 batteryInfos.insert_or_assign(info.id, info);
401 ALOGD("configureBatteryLocked rawBatteryId %d name %s", info.id, info.name.c_str());
402 }
403 return batteryInfos;
404}
405
406/**
407 * Read information about lights exposed through the sysfs path.
408 */
409static std::unordered_map<int32_t /*lightId*/, RawLightInfo> readLightsConfiguration(
410 const std::filesystem::path& sysfsRootPath) {
411 std::unordered_map<int32_t, RawLightInfo> lightInfos;
412 int32_t nextLightId = 0;
413 // Check if device has any lights.
414 const auto& paths = findSysfsNodes(sysfsRootPath, SysfsClass::LEDS);
415 for (const auto& nodePath : paths) {
416 RawLightInfo info;
417 info.id = ++nextLightId;
418 info.path = nodePath;
419 info.name = nodePath.filename();
420 info.maxBrightness = std::nullopt;
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000421
422 // Light name should follow the naming pattern <name>:<color>:<function>
423 // Refer kernel docs /leds/leds-class.html for valid supported LED names.
424 std::regex indexPattern("([a-zA-Z0-9_.:]*:)?([a-zA-Z0-9_.]*):([a-zA-Z0-9_.]*)");
425 std::smatch results;
426
427 if (std::regex_match(info.name, results, indexPattern)) {
428 // regex_match will return full match at index 0 and <name> at index 1. For RawLightInfo
429 // we only care about sections <color> and <function> which will be at index 2 and 3.
430 for (int i = 2; i <= 3; i++) {
431 const auto it = LIGHT_CLASSES.find(results.str(i));
432 if (it != LIGHT_CLASSES.end()) {
433 info.flags |= it->second;
434 }
Prabir Pradhancb42b472022-08-23 16:01:19 +0000435 }
Vaibhav Devmurari82b37d62022-09-12 13:36:48 +0000436
437 // Set name of the raw light to <function> which represents playerIDs for LEDs that
438 // turn on/off based on the current player ID (Refer to PeripheralController.cpp for
439 // player ID logic)
440 info.name = results.str(3);
Prabir Pradhancb42b472022-08-23 16:01:19 +0000441 }
442 // Scan the path for all the files
443 // Refer to https://www.kernel.org/doc/Documentation/leds/leds-class.txt
444 const auto& files = allFilesInPath(nodePath);
445 for (const auto& file : files) {
446 const auto it = LIGHT_CLASSES.find(file.filename().string());
447 if (it != LIGHT_CLASSES.end()) {
448 info.flags |= it->second;
449 // If the node has maximum brightness, read it
450 if (it->second == InputLightClass::MAX_BRIGHTNESS) {
451 std::string str;
452 if (base::ReadFileToString(file, &str)) {
453 info.maxBrightness = std::stoi(str);
454 }
455 }
456 }
457 }
458 lightInfos.insert_or_assign(info.id, info);
459 ALOGD("configureLightsLocked rawLightId %d name %s", info.id, info.name.c_str());
460 }
461 return lightInfos;
462}
463
Michael Wrightd02c5b62014-02-10 15:10:22 -0800464// --- Global Functions ---
465
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700466ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis,
467 ftl::Flags<InputDeviceClass> deviceClasses) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 // Touch devices get dibs on touch-related axes.
Chris Ye1b0c7342020-07-28 21:57:03 -0700469 if (deviceClasses.test(InputDeviceClass::TOUCH)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700471 case ABS_X:
472 case ABS_Y:
473 case ABS_PRESSURE:
474 case ABS_TOOL_WIDTH:
475 case ABS_DISTANCE:
476 case ABS_TILT_X:
477 case ABS_TILT_Y:
478 case ABS_MT_SLOT:
479 case ABS_MT_TOUCH_MAJOR:
480 case ABS_MT_TOUCH_MINOR:
481 case ABS_MT_WIDTH_MAJOR:
482 case ABS_MT_WIDTH_MINOR:
483 case ABS_MT_ORIENTATION:
484 case ABS_MT_POSITION_X:
485 case ABS_MT_POSITION_Y:
486 case ABS_MT_TOOL_TYPE:
487 case ABS_MT_BLOB_ID:
488 case ABS_MT_TRACKING_ID:
489 case ABS_MT_PRESSURE:
490 case ABS_MT_DISTANCE:
Chris Ye1b0c7342020-07-28 21:57:03 -0700491 return InputDeviceClass::TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492 }
493 }
494
Chris Yef59a2f42020-10-16 12:55:26 -0700495 if (deviceClasses.test(InputDeviceClass::SENSOR)) {
496 switch (axis) {
497 case ABS_X:
498 case ABS_Y:
499 case ABS_Z:
500 case ABS_RX:
501 case ABS_RY:
502 case ABS_RZ:
503 return InputDeviceClass::SENSOR;
504 }
505 }
506
Michael Wright842500e2015-03-13 17:32:02 -0700507 // External stylus gets the pressure axis
Chris Ye1b0c7342020-07-28 21:57:03 -0700508 if (deviceClasses.test(InputDeviceClass::EXTERNAL_STYLUS)) {
Michael Wright842500e2015-03-13 17:32:02 -0700509 if (axis == ABS_PRESSURE) {
Chris Ye1b0c7342020-07-28 21:57:03 -0700510 return InputDeviceClass::EXTERNAL_STYLUS;
Michael Wright842500e2015-03-13 17:32:02 -0700511 }
512 }
513
Michael Wrightd02c5b62014-02-10 15:10:22 -0800514 // Joystick devices get the rest.
Chris Ye1b0c7342020-07-28 21:57:03 -0700515 return deviceClasses & InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516}
517
Harry Cuttsea73eaa2023-01-16 17:55:46 +0000518// --- RawAbsoluteAxisInfo ---
519
520std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info) {
521 if (info.valid) {
522 out << "min=" << info.minValue << ", max=" << info.maxValue << ", flat=" << info.flat
523 << ", fuzz=" << info.fuzz << ", resolution=" << info.resolution;
524 } else {
525 out << "unknown range";
526 }
527 return out;
528}
529
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530// --- EventHub::Device ---
531
Prabir Pradhancb42b472022-08-23 16:01:19 +0000532EventHub::Device::Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier,
533 std::shared_ptr<const AssociatedDevice> assocDev)
Chris Ye989bb932020-07-04 16:18:59 -0700534 : fd(fd),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700535 id(id),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000536 path(std::move(path)),
537 identifier(std::move(identifier)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700538 classes(0),
539 configuration(nullptr),
540 virtualKeyMap(nullptr),
541 ffEffectPlaying(false),
542 ffEffectId(-1),
Prabir Pradhancb42b472022-08-23 16:01:19 +0000543 associatedDevice(std::move(assocDev)),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700544 controllerNumber(0),
545 enabled(true),
Chris Ye66fbac32020-07-06 20:36:43 -0700546 isVirtual(fd < 0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547
548EventHub::Device::~Device() {
549 close();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550}
551
552void EventHub::Device::close() {
553 if (fd >= 0) {
554 ::close(fd);
555 fd = -1;
556 }
557}
558
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700559status_t EventHub::Device::enable() {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100560 fd = open(path.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700561 if (fd < 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100562 ALOGE("could not open %s, %s\n", path.c_str(), strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700563 return -errno;
564 }
565 enabled = true;
566 return OK;
567}
568
569status_t EventHub::Device::disable() {
570 close();
571 enabled = false;
572 return OK;
573}
574
Chris Ye989bb932020-07-04 16:18:59 -0700575bool EventHub::Device::hasValidFd() const {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700576 return !isVirtual && enabled;
577}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800578
Chris Ye3a1e4462020-08-12 10:13:15 -0700579const std::shared_ptr<KeyCharacterMap> EventHub::Device::getKeyCharacterMap() const {
Chris Ye989bb932020-07-04 16:18:59 -0700580 return keyMap.keyCharacterMap;
581}
582
583template <std::size_t N>
584status_t EventHub::Device::readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray) {
585 if (!hasValidFd()) {
586 return BAD_VALUE;
587 }
588 if ((_IOC_SIZE(ioctlCode) == 0)) {
589 ioctlCode |= _IOC(0, 0, 0, bitArray.bytes());
590 }
591
592 typename BitArray<N>::Buffer buffer;
593 status_t ret = ioctl(fd, ioctlCode, buffer.data());
594 bitArray.loadFromBuffer(buffer);
595 return ret;
596}
597
598void EventHub::Device::configureFd() {
599 // Set fd parameters with ioctl, such as key repeat, suspend block, and clock type
600 if (classes.test(InputDeviceClass::KEYBOARD)) {
601 // Disable kernel key repeat since we handle it ourselves
602 unsigned int repeatRate[] = {0, 0};
603 if (ioctl(fd, EVIOCSREP, repeatRate)) {
604 ALOGW("Unable to disable kernel key repeat for %s: %s", path.c_str(), strerror(errno));
605 }
606 }
607
608 // Tell the kernel that we want to use the monotonic clock for reporting timestamps
609 // associated with input events. This is important because the input system
610 // uses the timestamps extensively and assumes they were recorded using the monotonic
611 // clock.
612 int clockId = CLOCK_MONOTONIC;
Chris Yef59a2f42020-10-16 12:55:26 -0700613 if (classes.test(InputDeviceClass::SENSOR)) {
614 // Each new sensor event should use the same time base as
615 // SystemClock.elapsedRealtimeNanos().
616 clockId = CLOCK_BOOTTIME;
617 }
Chris Ye989bb932020-07-04 16:18:59 -0700618 bool usingClockIoctl = !ioctl(fd, EVIOCSCLOCKID, &clockId);
619 ALOGI("usingClockIoctl=%s", toString(usingClockIoctl));
620}
621
622bool EventHub::Device::hasKeycodeLocked(int keycode) const {
623 if (!keyMap.haveKeyLayout()) {
624 return false;
625 }
626
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700627 std::vector<int32_t> scanCodes = keyMap.keyLayoutMap->findScanCodesForKey(keycode);
Chris Ye989bb932020-07-04 16:18:59 -0700628 const size_t N = scanCodes.size();
629 for (size_t i = 0; i < N && i <= KEY_MAX; i++) {
630 int32_t sc = scanCodes[i];
631 if (sc >= 0 && sc <= KEY_MAX && keyBitmask.test(sc)) {
632 return true;
633 }
634 }
635
636 return false;
637}
638
639void EventHub::Device::loadConfigurationLocked() {
640 configurationFile =
641 getInputDeviceConfigurationFilePathByDeviceIdentifier(identifier,
642 InputDeviceConfigurationFileType::
643 CONFIGURATION);
644 if (configurationFile.empty()) {
645 ALOGD("No input device configuration file found for device '%s'.", identifier.name.c_str());
646 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500647 android::base::Result<std::unique_ptr<PropertyMap>> propertyMap =
648 PropertyMap::load(configurationFile.c_str());
649 if (!propertyMap.ok()) {
Chris Ye989bb932020-07-04 16:18:59 -0700650 ALOGE("Error loading input device configuration file for device '%s'. "
651 "Using default configuration.",
652 identifier.name.c_str());
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500653 } else {
Siarhei Vishniakou4d9f9772020-09-02 22:28:29 -0500654 configuration = std::move(*propertyMap);
Chris Ye989bb932020-07-04 16:18:59 -0700655 }
656 }
657}
658
659bool EventHub::Device::loadVirtualKeyMapLocked() {
660 // The virtual key map is supplied by the kernel as a system board property file.
661 std::string propPath = "/sys/board_properties/virtualkeys.";
662 propPath += identifier.getCanonicalName();
663 if (access(propPath.c_str(), R_OK)) {
664 return false;
665 }
666 virtualKeyMap = VirtualKeyMap::load(propPath);
667 return virtualKeyMap != nullptr;
668}
669
670status_t EventHub::Device::loadKeyMapLocked() {
Siarhei Vishniakoud549b252020-08-11 11:25:26 -0500671 return keyMap.load(identifier, configuration.get());
Chris Ye989bb932020-07-04 16:18:59 -0700672}
673
674bool EventHub::Device::isExternalDeviceLocked() {
675 if (configuration) {
676 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700677 if (configuration->tryGetProperty("device.internal", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700678 return !value;
679 }
680 }
681 return identifier.bus == BUS_USB || identifier.bus == BUS_BLUETOOTH;
682}
683
684bool EventHub::Device::deviceHasMicLocked() {
685 if (configuration) {
686 bool value;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700687 if (configuration->tryGetProperty("audio.mic", value)) {
Chris Ye989bb932020-07-04 16:18:59 -0700688 return value;
689 }
690 }
691 return false;
692}
693
694void EventHub::Device::setLedStateLocked(int32_t led, bool on) {
695 int32_t sc;
696 if (hasValidFd() && mapLed(led, &sc) != NAME_NOT_FOUND) {
697 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -0700698 ev.input_event_sec = 0;
699 ev.input_event_usec = 0;
Chris Ye989bb932020-07-04 16:18:59 -0700700 ev.type = EV_LED;
701 ev.code = sc;
702 ev.value = on ? 1 : 0;
703
704 ssize_t nWrite;
705 do {
706 nWrite = write(fd, &ev, sizeof(struct input_event));
707 } while (nWrite == -1 && errno == EINTR);
708 }
709}
710
711void EventHub::Device::setLedForControllerLocked() {
712 for (int i = 0; i < MAX_CONTROLLER_LEDS; i++) {
713 setLedStateLocked(ALED_CONTROLLER_1 + i, controllerNumber == i + 1);
714 }
715}
716
717status_t EventHub::Device::mapLed(int32_t led, int32_t* outScanCode) const {
718 if (!keyMap.haveKeyLayout()) {
719 return NAME_NOT_FOUND;
720 }
721
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700722 std::optional<int32_t> scanCode = keyMap.keyLayoutMap->findScanCodeForLed(led);
723 if (scanCode.has_value()) {
724 if (*scanCode >= 0 && *scanCode <= LED_MAX && ledBitmask.test(*scanCode)) {
725 *outScanCode = *scanCode;
Chris Ye989bb932020-07-04 16:18:59 -0700726 return NO_ERROR;
727 }
728 }
729 return NAME_NOT_FOUND;
730}
731
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100732/**
733 * Get the capabilities for the current process.
734 * Crashes the system if unable to create / check / destroy the capabilities object.
735 */
736class Capabilities final {
737public:
738 explicit Capabilities() {
739 mCaps = cap_get_proc();
740 LOG_ALWAYS_FATAL_IF(mCaps == nullptr, "Could not get capabilities of the current process");
741 }
742
743 /**
744 * Check whether the current process has a specific capability
745 * in the set of effective capabilities.
746 * Return CAP_SET if the process has the requested capability
747 * Return CAP_CLEAR otherwise.
748 */
749 cap_flag_value_t checkEffectiveCapability(cap_value_t capability) {
750 cap_flag_value_t value;
751 const int result = cap_get_flag(mCaps, capability, CAP_EFFECTIVE, &value);
752 LOG_ALWAYS_FATAL_IF(result == -1, "Could not obtain the requested capability");
753 return value;
754 }
755
756 ~Capabilities() {
757 const int result = cap_free(mCaps);
758 LOG_ALWAYS_FATAL_IF(result == -1, "Could not release the capabilities structure");
759 }
760
761private:
762 cap_t mCaps;
763};
764
765static void ensureProcessCanBlockSuspend() {
766 Capabilities capabilities;
767 const bool canBlockSuspend =
768 capabilities.checkEffectiveCapability(CAP_BLOCK_SUSPEND) == CAP_SET;
769 LOG_ALWAYS_FATAL_IF(!canBlockSuspend,
770 "Input must be able to block suspend to properly process events");
771}
772
Michael Wrightd02c5b62014-02-10 15:10:22 -0800773// --- EventHub ---
774
Michael Wrightd02c5b62014-02-10 15:10:22 -0800775const int EventHub::EPOLL_MAX_EVENTS;
776
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700777EventHub::EventHub(void)
778 : mBuiltInKeyboardId(NO_BUILT_IN_KEYBOARD),
779 mNextDeviceId(1),
780 mControllerNumbers(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800781 mNeedToSendFinishedDeviceScan(false),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700782 mNeedToReopenDevices(false),
783 mNeedToScanDevices(true),
784 mPendingEventCount(0),
785 mPendingEventIndex(0),
786 mPendingINotify(false) {
Siarhei Vishniakou7a522bf2019-09-24 12:46:29 +0100787 ensureProcessCanBlockSuspend();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800788
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -0800789 mEpollFd = epoll_create1(EPOLL_CLOEXEC);
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800790 LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -0800791
Michael Wright8e9a8562022-02-09 13:44:29 +0000792 mINotifyFd = inotify_init1(IN_CLOEXEC);
Prabir Pradhan952e65b2022-06-23 17:49:55 +0000793 LOG_ALWAYS_FATAL_IF(mINotifyFd < 0, "Could not create inotify instance: %s", strerror(errno));
Usama Arifb27c8e62021-06-03 16:44:09 +0100794
795 std::error_code errorCode;
796 bool isDeviceInotifyAdded = false;
797 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
798 addDeviceInputInotify();
Philip Quinn39b81682019-01-09 22:20:39 -0800799 } else {
Usama Arifb27c8e62021-06-03 16:44:09 +0100800 addDeviceInotify();
801 isDeviceInotifyAdded = true;
802 if (errorCode) {
803 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
804 errorCode.message().c_str());
805 }
806 }
807
808 if (isV4lScanningEnabled() && !isDeviceInotifyAdded) {
809 addDeviceInotify();
810 } else {
Philip Quinn39b81682019-01-09 22:20:39 -0800811 ALOGI("Video device scanning disabled");
812 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakou2d0e9482019-09-24 12:52:47 +0100814 struct epoll_event eventItem = {};
815 eventItem.events = EPOLLIN | EPOLLWAKEUP;
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700816 eventItem.data.fd = mINotifyFd;
Siarhei Vishniakou951f3622018-12-12 19:45:42 -0800817 int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
819
820 int wakeFds[2];
Michael Wright8e9a8562022-02-09 13:44:29 +0000821 result = pipe2(wakeFds, O_CLOEXEC);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
823
824 mWakeReadPipeFd = wakeFds[0];
825 mWakeWritePipeFd = wakeFds[1];
826
827 result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
828 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700829 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830
831 result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
832 LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700833 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800834
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -0700835 eventItem.data.fd = mWakeReadPipeFd;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, &eventItem);
837 LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700838 errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839}
840
841EventHub::~EventHub(void) {
842 closeAllDevicesLocked();
843
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 ::close(mEpollFd);
845 ::close(mINotifyFd);
846 ::close(mWakeReadPipeFd);
847 ::close(mWakeWritePipeFd);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848}
849
Usama Arifb27c8e62021-06-03 16:44:09 +0100850/**
851 * On devices that don't have any input devices (like some development boards), the /dev/input
852 * directory will be absent. However, the user may still plug in an input device at a later time.
853 * Add watch for contents of /dev/input only when /dev/input appears.
854 */
855void EventHub::addDeviceInputInotify() {
856 mDeviceInputWd = inotify_add_watch(mINotifyFd, DEVICE_INPUT_PATH, IN_DELETE | IN_CREATE);
857 LOG_ALWAYS_FATAL_IF(mDeviceInputWd < 0, "Could not register INotify for %s: %s",
858 DEVICE_INPUT_PATH, strerror(errno));
859}
860
861void EventHub::addDeviceInotify() {
862 mDeviceWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
863 LOG_ALWAYS_FATAL_IF(mDeviceWd < 0, "Could not register INotify for %s: %s", DEVICE_PATH,
864 strerror(errno));
865}
866
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867InputDeviceIdentifier EventHub::getDeviceIdentifier(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000868 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800869 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700870 return device != nullptr ? device->identifier : InputDeviceIdentifier();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700873ftl::Flags<InputDeviceClass> EventHub::getDeviceClasses(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000874 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 Device* device = getDeviceLocked(deviceId);
Dominik Laskowski2f01d772022-03-23 16:01:29 -0700876 return device != nullptr ? device->classes : ftl::Flags<InputDeviceClass>(0);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877}
878
879int32_t EventHub::getDeviceControllerNumber(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +0000880 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700882 return device != nullptr ? device->controllerNumber : 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883}
884
885void EventHub::getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const {
Chris Ye87143712020-11-10 05:05:58 +0000886 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -0700888 if (device != nullptr && device->configuration) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 *outConfiguration = *device->configuration;
890 } else {
891 outConfiguration->clear();
892 }
893}
894
895status_t EventHub::getAbsoluteAxisInfo(int32_t deviceId, int axis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700896 RawAbsoluteAxisInfo* outAxisInfo) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 outAxisInfo->clear();
898
899 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000900 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901
902 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700903 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800904 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700905 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
906 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
907 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800908 return -errno;
909 }
910
911 if (info.minimum != info.maximum) {
912 outAxisInfo->valid = true;
913 outAxisInfo->minValue = info.minimum;
914 outAxisInfo->maxValue = info.maximum;
915 outAxisInfo->flat = info.flat;
916 outAxisInfo->fuzz = info.fuzz;
917 outAxisInfo->resolution = info.resolution;
918 }
919 return OK;
920 }
921 }
922 return -1;
923}
924
925bool EventHub::hasRelativeAxis(int32_t deviceId, int axis) const {
926 if (axis >= 0 && axis <= REL_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000927 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800928 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700929 return device != nullptr ? device->relBitmask.test(axis) : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800930 }
931 return false;
932}
933
934bool EventHub::hasInputProperty(int32_t deviceId, int property) const {
Chris Ye87143712020-11-10 05:05:58 +0000935 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936
Chris Ye989bb932020-07-04 16:18:59 -0700937 Device* device = getDeviceLocked(deviceId);
938 return property >= 0 && property <= INPUT_PROP_MAX && device != nullptr
939 ? device->propBitmask.test(property)
940 : false;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800941}
942
Chris Yef59a2f42020-10-16 12:55:26 -0700943bool EventHub::hasMscEvent(int32_t deviceId, int mscEvent) const {
944 std::scoped_lock _l(mLock);
945
946 Device* device = getDeviceLocked(deviceId);
947 return mscEvent >= 0 && mscEvent <= MSC_MAX && device != nullptr
948 ? device->mscBitmask.test(mscEvent)
949 : false;
950}
951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952int32_t EventHub::getScanCodeState(int32_t deviceId, int32_t scanCode) const {
953 if (scanCode >= 0 && scanCode <= KEY_MAX) {
Chris Ye87143712020-11-10 05:05:58 +0000954 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955
956 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700957 if (device != nullptr && device->hasValidFd() && device->keyBitmask.test(scanCode)) {
958 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
959 return device->keyState.test(scanCode) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800960 }
961 }
962 }
963 return AKEY_STATE_UNKNOWN;
964}
965
966int32_t EventHub::getKeyCodeState(int32_t deviceId, int32_t keyCode) const {
Chris Ye87143712020-11-10 05:05:58 +0000967 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800968
969 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -0700970 if (device != nullptr && device->hasValidFd() && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700971 std::vector<int32_t> scanCodes = device->keyMap.keyLayoutMap->findScanCodesForKey(keyCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972 if (scanCodes.size() != 0) {
Chris Ye66fbac32020-07-06 20:36:43 -0700973 if (device->readDeviceBitMask(EVIOCGKEY(0), device->keyState) >= 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800974 for (size_t i = 0; i < scanCodes.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800975 int32_t sc = scanCodes[i];
Chris Ye66fbac32020-07-06 20:36:43 -0700976 if (sc >= 0 && sc <= KEY_MAX && device->keyState.test(sc)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977 return AKEY_STATE_DOWN;
978 }
979 }
980 return AKEY_STATE_UP;
981 }
982 }
983 }
984 return AKEY_STATE_UNKNOWN;
985}
986
Philip Junker4af3b3d2021-12-14 10:36:55 +0100987int32_t EventHub::getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
988 std::scoped_lock _l(mLock);
989
990 Device* device = getDeviceLocked(deviceId);
991 if (device == nullptr || !device->hasValidFd() || device->keyMap.keyCharacterMap == nullptr ||
992 device->keyMap.keyLayoutMap == nullptr) {
993 return AKEYCODE_UNKNOWN;
994 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -0700995 std::vector<int32_t> scanCodes =
996 device->keyMap.keyLayoutMap->findScanCodesForKey(locationKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +0100997 if (scanCodes.empty()) {
998 ALOGW("Failed to get key code for key location: no scan code maps to key code %d for input"
999 "device %d",
1000 locationKeyCode, deviceId);
1001 return AKEYCODE_UNKNOWN;
1002 }
1003 if (scanCodes.size() > 1) {
1004 ALOGW("Multiple scan codes map to the same key code %d, returning only the first match",
1005 locationKeyCode);
1006 }
1007 int32_t outKeyCode;
1008 status_t mapKeyRes =
Harry Cutts33476232023-01-30 19:57:29 +00001009 device->getKeyCharacterMap()->mapKey(scanCodes[0], /*usageCode=*/0, &outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001010 switch (mapKeyRes) {
1011 case OK:
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001012 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001013 case NAME_NOT_FOUND:
1014 // key character map doesn't re-map this scanCode, hence the keyCode remains the same
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001015 outKeyCode = locationKeyCode;
1016 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001017 default:
1018 ALOGW("Failed to get key code for key location: Key character map returned error %s",
1019 statusToString(mapKeyRes).c_str());
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001020 outKeyCode = AKEYCODE_UNKNOWN;
1021 break;
Philip Junker4af3b3d2021-12-14 10:36:55 +01001022 }
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001023 // Remap if there is a Key remapping added to the KCM and return the remapped key
1024 return device->getKeyCharacterMap()->applyKeyRemapping(outKeyCode);
Philip Junker4af3b3d2021-12-14 10:36:55 +01001025}
1026
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027int32_t EventHub::getSwitchState(int32_t deviceId, int32_t sw) const {
1028 if (sw >= 0 && sw <= SW_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001029 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001030
1031 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001032 if (device != nullptr && device->hasValidFd() && device->swBitmask.test(sw)) {
1033 if (device->readDeviceBitMask(EVIOCGSW(0), device->swState) >= 0) {
1034 return device->swState.test(sw) ? AKEY_STATE_DOWN : AKEY_STATE_UP;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035 }
1036 }
1037 }
1038 return AKEY_STATE_UNKNOWN;
1039}
1040
1041status_t EventHub::getAbsoluteAxisValue(int32_t deviceId, int32_t axis, int32_t* outValue) const {
1042 *outValue = 0;
1043
1044 if (axis >= 0 && axis <= ABS_MAX) {
Chris Ye87143712020-11-10 05:05:58 +00001045 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001046
1047 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001048 if (device != nullptr && device->hasValidFd() && device->absBitmask.test(axis)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 struct input_absinfo info;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001050 if (ioctl(device->fd, EVIOCGABS(axis), &info)) {
1051 ALOGW("Error reading absolute controller %d for device %s fd %d, errno=%d", axis,
1052 device->identifier.name.c_str(), device->fd, errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 return -errno;
1054 }
1055
1056 *outValue = info.value;
1057 return OK;
1058 }
1059 }
1060 return -1;
1061}
1062
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001063bool EventHub::markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001064 uint8_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001065 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066
1067 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001068 if (device != nullptr && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001069 for (size_t codeIndex = 0; codeIndex < keyCodes.size(); codeIndex++) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001070 std::vector<int32_t> scanCodes =
1071 device->keyMap.keyLayoutMap->findScanCodesForKey(keyCodes[codeIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001072
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001073 // check the possible scan codes identified by the layout map against the
1074 // map of codes actually emitted by the driver
Siarhei Vishniakou74007942022-06-13 13:57:47 -07001075 for (const int32_t scanCode : scanCodes) {
1076 if (device->keyBitmask.test(scanCode)) {
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001077 outFlags[codeIndex] = 1;
1078 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079 }
1080 }
1081 }
1082 return true;
1083 }
1084 return false;
1085}
1086
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001087void EventHub::addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, int32_t toKeyCode) const {
1088 std::scoped_lock _l(mLock);
1089 Device* device = getDeviceLocked(deviceId);
1090 if (device == nullptr) {
1091 return;
1092 }
1093 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1094 if (kcm) {
1095 kcm->addKeyRemapping(fromKeyCode, toKeyCode);
1096 }
1097}
1098
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001099status_t EventHub::mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
1100 int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const {
Chris Ye87143712020-11-10 05:05:58 +00001101 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 Device* device = getDeviceLocked(deviceId);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001103 status_t status = NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001104
Chris Ye66fbac32020-07-06 20:36:43 -07001105 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001106 // Check the key character map first.
Chris Ye3a1e4462020-08-12 10:13:15 -07001107 const std::shared_ptr<KeyCharacterMap> kcm = device->getKeyCharacterMap();
1108 if (kcm) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001109 if (!kcm->mapKey(scanCode, usageCode, outKeycode)) {
1110 *outFlags = 0;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001111 status = NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112 }
1113 }
1114
1115 // Check the key layout next.
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001116 if (status != NO_ERROR && device->keyMap.haveKeyLayout()) {
Siarhei Vishniakou592bac22018-11-08 19:42:38 -08001117 if (!device->keyMap.keyLayoutMap->mapKey(scanCode, usageCode, outKeycode, outFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001118 status = NO_ERROR;
1119 }
1120 }
1121
1122 if (status == NO_ERROR) {
Chris Ye3a1e4462020-08-12 10:13:15 -07001123 if (kcm) {
Vaibhav Devmuraricbba14c2022-10-10 16:54:49 +00001124 // Remap keys based on user-defined key remappings and key behavior defined in the
1125 // corresponding kcm file
1126 *outKeycode = kcm->applyKeyRemapping(*outKeycode);
1127
1128 // Remap keys based on Key behavior defined in KCM file
1129 std::tie(*outKeycode, *outMetaState) =
1130 kcm->applyKeyBehavior(*outKeycode, metaState);
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001131 } else {
1132 *outMetaState = metaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 }
1134 }
1135 }
1136
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07001137 if (status != NO_ERROR) {
1138 *outKeycode = 0;
1139 *outFlags = 0;
1140 *outMetaState = metaState;
1141 }
1142
1143 return status;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144}
1145
1146status_t EventHub::mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const {
Chris Ye87143712020-11-10 05:05:58 +00001147 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 Device* device = getDeviceLocked(deviceId);
1149
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001150 if (device == nullptr || !device->keyMap.haveKeyLayout()) {
1151 return NAME_NOT_FOUND;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001152 }
Siarhei Vishniakouef1564c2022-05-18 09:45:54 -07001153 std::optional<AxisInfo> info = device->keyMap.keyLayoutMap->mapAxis(scanCode);
1154 if (!info.has_value()) {
1155 return NAME_NOT_FOUND;
1156 }
1157 *outAxisInfo = *info;
1158 return NO_ERROR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159}
1160
Chris Yef59a2f42020-10-16 12:55:26 -07001161base::Result<std::pair<InputDeviceSensorType, int32_t>> EventHub::mapSensor(int32_t deviceId,
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001162 int32_t absCode) const {
Chris Yef59a2f42020-10-16 12:55:26 -07001163 std::scoped_lock _l(mLock);
1164 Device* device = getDeviceLocked(deviceId);
1165
1166 if (device != nullptr && device->keyMap.haveKeyLayout()) {
1167 return device->keyMap.keyLayoutMap->mapSensor(absCode);
1168 }
1169 return Errorf("Device not found or device has no key layout.");
1170}
1171
Chris Yee2b1e5c2021-03-10 22:45:12 -08001172// Gets the battery info map from battery ID to RawBatteryInfo of the miscellaneous device
1173// associated with the device ID. Returns an empty map if no miscellaneous device found.
1174const std::unordered_map<int32_t, RawBatteryInfo>& EventHub::getBatteryInfoLocked(
1175 int32_t deviceId) const {
1176 static const std::unordered_map<int32_t, RawBatteryInfo> EMPTY_BATTERY_INFO = {};
1177 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001178 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001179 return EMPTY_BATTERY_INFO;
1180 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001181 return device->associatedDevice->batteryInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001182}
1183
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001184std::vector<int32_t> EventHub::getRawBatteryIds(int32_t deviceId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001185 std::scoped_lock _l(mLock);
1186 std::vector<int32_t> batteryIds;
1187
Prabir Pradhan51894782022-08-23 16:29:10 +00001188 for (const auto& [id, info] : getBatteryInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001189 batteryIds.push_back(id);
1190 }
1191
1192 return batteryIds;
1193}
1194
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001195std::optional<RawBatteryInfo> EventHub::getRawBatteryInfo(int32_t deviceId,
1196 int32_t batteryId) const {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001197 std::scoped_lock _l(mLock);
1198
1199 const auto infos = getBatteryInfoLocked(deviceId);
1200
1201 auto it = infos.find(batteryId);
1202 if (it != infos.end()) {
1203 return it->second;
1204 }
1205
1206 return std::nullopt;
1207}
1208
1209// Gets the light info map from light ID to RawLightInfo of the miscellaneous device associated
Prabir Pradhan51894782022-08-23 16:29:10 +00001210// with the device ID. Returns an empty map if no miscellaneous device found.
Chris Yee2b1e5c2021-03-10 22:45:12 -08001211const std::unordered_map<int32_t, RawLightInfo>& EventHub::getLightInfoLocked(
1212 int32_t deviceId) const {
1213 static const std::unordered_map<int32_t, RawLightInfo> EMPTY_LIGHT_INFO = {};
1214 Device* device = getDeviceLocked(deviceId);
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001215 if (device == nullptr || !device->associatedDevice) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001216 return EMPTY_LIGHT_INFO;
1217 }
Chris Ye1dd2e5c2021-04-04 23:12:41 -07001218 return device->associatedDevice->lightInfos;
Chris Yee2b1e5c2021-03-10 22:45:12 -08001219}
1220
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001221std::vector<int32_t> EventHub::getRawLightIds(int32_t deviceId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001222 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001223 std::vector<int32_t> lightIds;
1224
Prabir Pradhan51894782022-08-23 16:29:10 +00001225 for (const auto& [id, info] : getLightInfoLocked(deviceId)) {
Chris Yee2b1e5c2021-03-10 22:45:12 -08001226 lightIds.push_back(id);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001227 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001228
Chris Ye3fdbfef2021-01-06 18:45:18 -08001229 return lightIds;
1230}
1231
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001232std::optional<RawLightInfo> EventHub::getRawLightInfo(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001233 std::scoped_lock _l(mLock);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001234
Chris Yee2b1e5c2021-03-10 22:45:12 -08001235 const auto infos = getLightInfoLocked(deviceId);
1236
1237 auto it = infos.find(lightId);
1238 if (it != infos.end()) {
1239 return it->second;
Chris Ye3fdbfef2021-01-06 18:45:18 -08001240 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001241
Chris Ye3fdbfef2021-01-06 18:45:18 -08001242 return std::nullopt;
1243}
1244
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001245std::optional<int32_t> EventHub::getLightBrightness(int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001246 std::scoped_lock _l(mLock);
1247
Chris Yee2b1e5c2021-03-10 22:45:12 -08001248 const auto infos = getLightInfoLocked(deviceId);
1249 auto it = infos.find(lightId);
1250 if (it == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001251 return std::nullopt;
1252 }
1253 std::string buffer;
1254 if (!base::ReadFileToString(it->second.path / LIGHT_NODES.at(InputLightClass::BRIGHTNESS),
1255 &buffer)) {
1256 return std::nullopt;
1257 }
1258 return std::stoi(buffer);
1259}
1260
1261std::optional<std::unordered_map<LightColor, int32_t>> EventHub::getLightIntensities(
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001262 int32_t deviceId, int32_t lightId) const {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001263 std::scoped_lock _l(mLock);
1264
Chris Yee2b1e5c2021-03-10 22:45:12 -08001265 const auto infos = getLightInfoLocked(deviceId);
1266 auto lightIt = infos.find(lightId);
1267 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001268 return std::nullopt;
1269 }
1270
1271 auto ret =
1272 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1273
1274 if (!ret.has_value()) {
1275 return std::nullopt;
1276 }
1277 std::array<LightColor, COLOR_NUM> colors = ret.value();
1278
1279 std::string intensityStr;
1280 if (!base::ReadFileToString(lightIt->second.path /
1281 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY),
1282 &intensityStr)) {
1283 return std::nullopt;
1284 }
1285
1286 // Intensity node outputs 3 color values
1287 std::regex intensityPattern("([0-9]+)\\s([0-9]+)\\s([0-9]+)[\\n]");
1288 std::smatch results;
1289
1290 if (!std::regex_match(intensityStr, results, intensityPattern)) {
1291 return std::nullopt;
1292 }
1293 std::unordered_map<LightColor, int32_t> intensities;
1294 for (size_t i = 1; i < results.size(); i++) {
1295 int value = std::stoi(results[i].str());
1296 intensities.emplace(colors[i - 1], value);
1297 }
1298 return intensities;
1299}
1300
1301void EventHub::setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) {
1302 std::scoped_lock _l(mLock);
1303
Chris Yee2b1e5c2021-03-10 22:45:12 -08001304 const auto infos = getLightInfoLocked(deviceId);
1305 auto lightIt = infos.find(lightId);
1306 if (lightIt == infos.end()) {
1307 ALOGE("%s lightId %d not found ", __func__, lightId);
Chris Ye3fdbfef2021-01-06 18:45:18 -08001308 return;
1309 }
1310
1311 if (!base::WriteStringToFile(std::to_string(brightness),
1312 lightIt->second.path /
1313 LIGHT_NODES.at(InputLightClass::BRIGHTNESS))) {
1314 ALOGE("Can not write to file, error: %s", strerror(errno));
1315 }
1316}
1317
1318void EventHub::setLightIntensities(int32_t deviceId, int32_t lightId,
1319 std::unordered_map<LightColor, int32_t> intensities) {
1320 std::scoped_lock _l(mLock);
1321
Chris Yee2b1e5c2021-03-10 22:45:12 -08001322 const auto infos = getLightInfoLocked(deviceId);
1323 auto lightIt = infos.find(lightId);
1324 if (lightIt == infos.end()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08001325 ALOGE("Light Id %d does not exist.", lightId);
1326 return;
1327 }
1328
1329 auto ret =
1330 getColorIndexArray(lightIt->second.path / LIGHT_NODES.at(InputLightClass::MULTI_INDEX));
1331
1332 if (!ret.has_value()) {
1333 return;
1334 }
1335 std::array<LightColor, COLOR_NUM> colors = ret.value();
1336
1337 std::string rgbStr;
1338 for (size_t i = 0; i < COLOR_NUM; i++) {
1339 auto it = intensities.find(colors[i]);
1340 if (it != intensities.end()) {
1341 rgbStr += std::to_string(it->second);
1342 // Insert space between colors
1343 if (i < COLOR_NUM - 1) {
1344 rgbStr += " ";
1345 }
1346 }
1347 }
1348 // Append new line
1349 rgbStr += "\n";
1350
1351 if (!base::WriteStringToFile(rgbStr,
1352 lightIt->second.path /
1353 LIGHT_NODES.at(InputLightClass::MULTI_INTENSITY))) {
1354 ALOGE("Can not write to file, error: %s", strerror(errno));
1355 }
1356}
1357
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001358std::optional<RawLayoutInfo> EventHub::getRawLayoutInfo(int32_t deviceId) const {
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001359 std::scoped_lock _l(mLock);
1360 Device* device = getDeviceLocked(deviceId);
1361 if (device == nullptr || !device->associatedDevice) {
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001362 return std::nullopt;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001363 }
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001364 return device->associatedDevice->layoutInfo;
Vaibhav Devmuraridd82b8e2022-08-16 15:34:01 +00001365}
1366
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001367void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
Chris Ye87143712020-11-10 05:05:58 +00001368 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001369
1370 mExcludedDevices = devices;
1371}
1372
1373bool EventHub::hasScanCode(int32_t deviceId, int32_t scanCode) const {
Chris Ye87143712020-11-10 05:05:58 +00001374 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001375 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001376 if (device != nullptr && scanCode >= 0 && scanCode <= KEY_MAX) {
1377 return device->keyBitmask.test(scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001378 }
1379 return false;
1380}
1381
Arthur Hungcb40a002021-08-03 14:31:01 +00001382bool EventHub::hasKeyCode(int32_t deviceId, int32_t keyCode) const {
1383 std::scoped_lock _l(mLock);
1384 Device* device = getDeviceLocked(deviceId);
1385 if (device != nullptr) {
1386 return device->hasKeycodeLocked(keyCode);
1387 }
1388 return false;
1389}
1390
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391bool EventHub::hasLed(int32_t deviceId, int32_t led) const {
Chris Ye87143712020-11-10 05:05:58 +00001392 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393 Device* device = getDeviceLocked(deviceId);
1394 int32_t sc;
Chris Ye989bb932020-07-04 16:18:59 -07001395 if (device != nullptr && device->mapLed(led, &sc) == NO_ERROR) {
Chris Ye66fbac32020-07-06 20:36:43 -07001396 return device->ledBitmask.test(sc);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001397 }
1398 return false;
1399}
1400
1401void EventHub::setLedState(int32_t deviceId, int32_t led, bool on) {
Chris Ye87143712020-11-10 05:05:58 +00001402 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001403 Device* device = getDeviceLocked(deviceId);
Chris Ye989bb932020-07-04 16:18:59 -07001404 if (device != nullptr && device->hasValidFd()) {
1405 device->setLedStateLocked(led, on);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001406 }
1407}
1408
1409void EventHub::getVirtualKeyDefinitions(int32_t deviceId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001410 std::vector<VirtualKeyDefinition>& outVirtualKeys) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001411 outVirtualKeys.clear();
1412
Chris Ye87143712020-11-10 05:05:58 +00001413 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001414 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001415 if (device != nullptr && device->virtualKeyMap) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001416 const std::vector<VirtualKeyDefinition> virtualKeys =
1417 device->virtualKeyMap->getVirtualKeys();
1418 outVirtualKeys.insert(outVirtualKeys.end(), virtualKeys.begin(), virtualKeys.end());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001419 }
1420}
1421
Chris Ye3a1e4462020-08-12 10:13:15 -07001422const std::shared_ptr<KeyCharacterMap> EventHub::getKeyCharacterMap(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001423 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001424 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001425 if (device != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001426 return device->getKeyCharacterMap();
1427 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001428 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001429}
1430
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001431// If provided map is null, it will reset key character map to default KCM.
Chris Ye3a1e4462020-08-12 10:13:15 -07001432bool EventHub::setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) {
Chris Ye87143712020-11-10 05:05:58 +00001433 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001434 Device* device = getDeviceLocked(deviceId);
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001435 if (device == nullptr || device->keyMap.keyCharacterMap == nullptr) {
Philip Junker90bc9492021-12-10 18:39:42 +01001436 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
Vaibhav Devmurari23e8ae92022-12-29 12:07:56 +00001438 if (map == nullptr) {
1439 device->keyMap.keyCharacterMap->clearLayoutOverlay();
1440 return true;
1441 }
Philip Junker90bc9492021-12-10 18:39:42 +01001442 device->keyMap.keyCharacterMap->combine(*map);
1443 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001444}
1445
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001446static std::string generateDescriptor(InputDeviceIdentifier& identifier) {
1447 std::string rawDescriptor;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001448 rawDescriptor += StringPrintf(":%04x:%04x:", identifier.vendor, identifier.product);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 // TODO add handling for USB devices to not uniqueify kbs that show up twice
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001450 if (!identifier.uniqueId.empty()) {
1451 rawDescriptor += "uniqueId:";
1452 rawDescriptor += identifier.uniqueId;
Josh Bartel938632f2022-07-19 15:34:22 -05001453 }
1454 if (identifier.nonce != 0) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001455 rawDescriptor += StringPrintf("nonce:%04x", identifier.nonce);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001456 }
1457
1458 if (identifier.vendor == 0 && identifier.product == 0) {
1459 // If we don't know the vendor and product id, then the device is probably
1460 // built-in so we need to rely on other information to uniquely identify
1461 // the input device. Usually we try to avoid relying on the device name or
1462 // location but for built-in input device, they are unlikely to ever change.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001463 if (!identifier.name.empty()) {
1464 rawDescriptor += "name:";
1465 rawDescriptor += identifier.name;
1466 } else if (!identifier.location.empty()) {
1467 rawDescriptor += "location:";
1468 rawDescriptor += identifier.location;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001469 }
1470 }
1471 identifier.descriptor = sha1(rawDescriptor);
1472 return rawDescriptor;
1473}
1474
1475void EventHub::assignDescriptorLocked(InputDeviceIdentifier& identifier) {
1476 // Compute a device descriptor that uniquely identifies the device.
1477 // The descriptor is assumed to be a stable identifier. Its value should not
1478 // change between reboots, reconnections, firmware updates or new releases
1479 // of Android. In practice we sometimes get devices that cannot be uniquely
1480 // identified. In this case we enforce uniqueness between connected devices.
1481 // Ideally, we also want the descriptor to be short and relatively opaque.
Josh Bartel938632f2022-07-19 15:34:22 -05001482 // Note that we explicitly do not use the path or location for external devices
1483 // as their path or location will change as they are plugged/unplugged or moved
1484 // to different ports. We do fallback to using name and location in the case of
1485 // internal devices which are detected by the vendor and product being 0 in
1486 // generateDescriptor. If two identical descriptors are detected we will fallback
1487 // to using a 'nonce' and incrementing it until the new descriptor no longer has
1488 // a match with any existing descriptors.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489
1490 identifier.nonce = 0;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001491 std::string rawDescriptor = generateDescriptor(identifier);
Josh Bartel938632f2022-07-19 15:34:22 -05001492 // Enforce that the generated descriptor is unique.
1493 while (hasDeviceWithDescriptorLocked(identifier.descriptor)) {
1494 identifier.nonce++;
1495 rawDescriptor = generateDescriptor(identifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001496 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001497 ALOGV("Created descriptor: raw=%s, cooked=%s", rawDescriptor.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001498 identifier.descriptor.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001499}
1500
Prabir Pradhancb42b472022-08-23 16:01:19 +00001501std::shared_ptr<const EventHub::AssociatedDevice> EventHub::obtainAssociatedDeviceLocked(
1502 const std::filesystem::path& devicePath) const {
1503 const std::optional<std::filesystem::path> sysfsRootPathOpt =
1504 getSysfsRootPath(devicePath.c_str());
1505 if (!sysfsRootPathOpt) {
1506 return nullptr;
1507 }
1508
1509 const auto& path = *sysfsRootPathOpt;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001510
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001511 std::shared_ptr<const AssociatedDevice> associatedDevice = std::make_shared<AssociatedDevice>(
Prabir Pradhancb42b472022-08-23 16:01:19 +00001512 AssociatedDevice{.sysfsRootPath = path,
1513 .batteryInfos = readBatteryConfiguration(path),
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00001514 .lightInfos = readLightsConfiguration(path),
1515 .layoutInfo = readLayoutConfiguration(path)});
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00001516
1517 bool associatedDeviceChanged = false;
1518 for (const auto& [id, dev] : mDevices) {
1519 if (dev->associatedDevice && dev->associatedDevice->sysfsRootPath == path) {
1520 if (*associatedDevice != *dev->associatedDevice) {
1521 associatedDeviceChanged = true;
1522 dev->associatedDevice = associatedDevice;
1523 }
1524 associatedDevice = dev->associatedDevice;
1525 }
1526 }
1527 ALOGI_IF(associatedDeviceChanged,
1528 "The AssociatedDevice changed for path '%s'. Using new AssociatedDevice: %s",
1529 path.c_str(), associatedDevice->dump().c_str());
1530
1531 return associatedDevice;
Prabir Pradhancb42b472022-08-23 16:01:19 +00001532}
1533
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001534void EventHub::vibrate(int32_t deviceId, const VibrationElement& element) {
Chris Ye87143712020-11-10 05:05:58 +00001535 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001537 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001538 ff_effect effect;
1539 memset(&effect, 0, sizeof(effect));
1540 effect.type = FF_RUMBLE;
1541 effect.id = device->ffEffectId;
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001542 // evdev FF_RUMBLE effect only supports two channels of vibration.
Chris Ye6393a262020-08-04 19:41:36 -07001543 effect.u.rumble.strong_magnitude = element.getMagnitude(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1544 effect.u.rumble.weak_magnitude = element.getMagnitude(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
Nathaniel R. Lewiscacd69a2019-08-12 22:07:00 +00001545 effect.replay.length = element.duration.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 effect.replay.delay = 0;
1547 if (ioctl(device->fd, EVIOCSFF, &effect)) {
1548 ALOGW("Could not upload force feedback effect to device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001549 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 return;
1551 }
1552 device->ffEffectId = effect.id;
1553
1554 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001555 ev.input_event_sec = 0;
1556 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001557 ev.type = EV_FF;
1558 ev.code = device->ffEffectId;
1559 ev.value = 1;
1560 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1561 ALOGW("Could not start force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001562 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001563 return;
1564 }
1565 device->ffEffectPlaying = true;
1566 }
1567}
1568
1569void EventHub::cancelVibrate(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00001570 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001571 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07001572 if (device != nullptr && device->hasValidFd()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 if (device->ffEffectPlaying) {
1574 device->ffEffectPlaying = false;
1575
1576 struct input_event ev;
Colin Cross5b799302022-10-18 21:52:41 -07001577 ev.input_event_sec = 0;
1578 ev.input_event_usec = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001579 ev.type = EV_FF;
1580 ev.code = device->ffEffectId;
1581 ev.value = 0;
1582 if (write(device->fd, &ev, sizeof(ev)) != sizeof(ev)) {
1583 ALOGW("Could not stop force feedback effect on device %s due to error %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001584 device->identifier.name.c_str(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 return;
1586 }
1587 }
1588 }
1589}
1590
Prabir Pradhanae4ff282022-08-23 16:21:39 +00001591std::vector<int32_t> EventHub::getVibratorIds(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00001592 std::scoped_lock _l(mLock);
1593 std::vector<int32_t> vibrators;
1594 Device* device = getDeviceLocked(deviceId);
1595 if (device != nullptr && device->hasValidFd() &&
1596 device->classes.test(InputDeviceClass::VIBRATOR)) {
1597 vibrators.push_back(FF_STRONG_MAGNITUDE_CHANNEL_IDX);
1598 vibrators.push_back(FF_WEAK_MAGNITUDE_CHANNEL_IDX);
1599 }
1600 return vibrators;
1601}
1602
Josh Bartel938632f2022-07-19 15:34:22 -05001603/**
1604 * Checks both mDevices and mOpeningDevices for a device with the descriptor passed.
1605 */
1606bool EventHub::hasDeviceWithDescriptorLocked(const std::string& descriptor) const {
1607 for (const auto& device : mOpeningDevices) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001608 if (descriptor == device->identifier.descriptor) {
Josh Bartel938632f2022-07-19 15:34:22 -05001609 return true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001610 }
1611 }
Josh Bartel938632f2022-07-19 15:34:22 -05001612
1613 for (const auto& [id, device] : mDevices) {
1614 if (descriptor == device->identifier.descriptor) {
1615 return true;
1616 }
1617 }
1618 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001619}
1620
1621EventHub::Device* EventHub::getDeviceLocked(int32_t deviceId) const {
Prabir Pradhancae4b3a2019-02-05 18:51:32 -08001622 if (deviceId == ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001623 deviceId = mBuiltInKeyboardId;
1624 }
Chris Ye989bb932020-07-04 16:18:59 -07001625 const auto& it = mDevices.find(deviceId);
1626 return it != mDevices.end() ? it->second.get() : nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001627}
1628
Chris Ye8594e192020-07-14 10:34:06 -07001629EventHub::Device* EventHub::getDeviceByPathLocked(const std::string& devicePath) const {
Chris Ye989bb932020-07-04 16:18:59 -07001630 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001631 if (device->path == devicePath) {
Chris Ye989bb932020-07-04 16:18:59 -07001632 return device.get();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001633 }
1634 }
Yi Kong9b14ac62018-07-17 13:48:38 -07001635 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001636}
1637
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001638/**
1639 * The file descriptor could be either input device, or a video device (associated with a
1640 * specific input device). Check both cases here, and return the device that this event
1641 * belongs to. Caller can compare the fd's once more to determine event type.
1642 * Looks through all input devices, and only attached video devices. Unattached video
1643 * devices are ignored.
1644 */
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001645EventHub::Device* EventHub::getDeviceByFdLocked(int fd) const {
Chris Ye989bb932020-07-04 16:18:59 -07001646 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001647 if (device->fd == fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001648 // This is an input device event
Chris Ye989bb932020-07-04 16:18:59 -07001649 return device.get();
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001650 }
1651 if (device->videoDevice && device->videoDevice->getFd() == fd) {
1652 // This is a video device event
Chris Ye989bb932020-07-04 16:18:59 -07001653 return device.get();
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001654 }
1655 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001656 // We do not check mUnattachedVideoDevices here because they should not participate in epoll,
1657 // and therefore should never be looked up by fd.
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001658 return nullptr;
1659}
1660
Chris Yee2b1e5c2021-03-10 22:45:12 -08001661std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001662 std::filesystem::path batteryPath;
1663 {
1664 // Do not read the sysfs node to get the battery state while holding
1665 // the EventHub lock. For some peripheral devices, reading battery state
1666 // can be broken and take 5+ seconds. Holding the lock in this case would
1667 // block all other event processing during this time. For now, we assume this
1668 // call never happens on the InputReader thread and read the sysfs node outside
1669 // the lock to prevent event processing from being blocked by this call.
1670 std::scoped_lock _l(mLock);
Kim Low03ea0352020-11-06 12:45:07 -08001671
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001672 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001673 auto it = infos.find(batteryId);
1674 if (it == infos.end()) {
1675 return std::nullopt;
1676 }
1677 batteryPath = it->second.path;
1678 } // release lock
1679
Chris Yee2b1e5c2021-03-10 22:45:12 -08001680 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001681
1682 // Some devices report battery capacity as an integer through the "capacity" file
Andy Chenf9f1a022022-08-29 20:07:10 -04001683 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001684 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001685 return std::stoi(base::Trim(buffer));
Kim Low03ea0352020-11-06 12:45:07 -08001686 }
1687
1688 // Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
1689 // These values are taken from kernel source code include/linux/power_supply.h
Andy Chenf9f1a022022-08-29 20:07:10 -04001690 if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001691 &buffer)) {
Chris Yed1936772021-02-22 10:30:40 -08001692 // Remove any white space such as trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001693 const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
1694 if (levelIt != BATTERY_LEVEL.end()) {
1695 return levelIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001696 }
1697 }
Chris Yee2b1e5c2021-03-10 22:45:12 -08001698
Kim Low03ea0352020-11-06 12:45:07 -08001699 return std::nullopt;
1700}
1701
Chris Yee2b1e5c2021-03-10 22:45:12 -08001702std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
Andy Chenf9f1a022022-08-29 20:07:10 -04001703 std::filesystem::path batteryPath;
1704 {
1705 // Do not read the sysfs node to get the battery state while holding
1706 // the EventHub lock. For some peripheral devices, reading battery state
1707 // can be broken and take 5+ seconds. Holding the lock in this case would
1708 // block all other event processing during this time. For now, we assume this
1709 // call never happens on the InputReader thread and read the sysfs node outside
1710 // the lock to prevent event processing from being blocked by this call.
1711 std::scoped_lock _l(mLock);
1712
Prabir Pradhane287ecd2022-09-07 21:18:05 +00001713 const auto& infos = getBatteryInfoLocked(deviceId);
Andy Chenf9f1a022022-08-29 20:07:10 -04001714 auto it = infos.find(batteryId);
1715 if (it == infos.end()) {
1716 return std::nullopt;
1717 }
1718 batteryPath = it->second.path;
1719 } // release lock
1720
Chris Yee2b1e5c2021-03-10 22:45:12 -08001721 std::string buffer;
Kim Low03ea0352020-11-06 12:45:07 -08001722
Andy Chenf9f1a022022-08-29 20:07:10 -04001723 if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
Chris Yee2b1e5c2021-03-10 22:45:12 -08001724 &buffer)) {
Kim Low03ea0352020-11-06 12:45:07 -08001725 ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
1726 return std::nullopt;
1727 }
1728
Chris Yed1936772021-02-22 10:30:40 -08001729 // Remove white space like trailing new line
Chris Yee2b1e5c2021-03-10 22:45:12 -08001730 const auto statusIt = BATTERY_STATUS.find(base::Trim(buffer));
1731 if (statusIt != BATTERY_STATUS.end()) {
1732 return statusIt->second;
Kim Low03ea0352020-11-06 12:45:07 -08001733 }
1734
1735 return std::nullopt;
1736}
1737
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001738std::vector<RawEvent> EventHub::getEvents(int timeoutMillis) {
Chris Ye87143712020-11-10 05:05:58 +00001739 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001741 std::array<input_event, EVENT_BUFFER_SIZE> readBuffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001743 std::vector<RawEvent> events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001744 bool awoken = false;
1745 for (;;) {
1746 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
1747
1748 // Reopen input devices if needed.
1749 if (mNeedToReopenDevices) {
1750 mNeedToReopenDevices = false;
1751
1752 ALOGI("Reopening all input devices due to a configuration change.");
1753
1754 closeAllDevicesLocked();
1755 mNeedToScanDevices = true;
1756 break; // return to the caller before we actually rescan
1757 }
1758
1759 // Report any devices that had last been added/removed.
Chris Ye989bb932020-07-04 16:18:59 -07001760 for (auto it = mClosingDevices.begin(); it != mClosingDevices.end();) {
1761 std::unique_ptr<Device> device = std::move(*it);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001762 ALOGV("Reporting device closed: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001763 const int32_t deviceId = (device->id == mBuiltInKeyboardId)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001764 ? ReservedInputDeviceId::BUILT_IN_KEYBOARD_ID
1765 : device->id;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001766 events.push_back({
1767 .when = now,
1768 .deviceId = deviceId,
1769 .type = DEVICE_REMOVED,
1770 });
Chris Ye989bb932020-07-04 16:18:59 -07001771 it = mClosingDevices.erase(it);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001772 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001773 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001774 break;
1775 }
1776 }
1777
1778 if (mNeedToScanDevices) {
1779 mNeedToScanDevices = false;
1780 scanDevicesLocked();
1781 mNeedToSendFinishedDeviceScan = true;
1782 }
1783
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001784 while (!mOpeningDevices.empty()) {
1785 std::unique_ptr<Device> device = std::move(*mOpeningDevices.rbegin());
1786 mOpeningDevices.pop_back();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001787 ALOGV("Reporting device opened: id=%d, name=%s\n", device->id, device->path.c_str());
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001788 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
1789 events.push_back({
1790 .when = now,
1791 .deviceId = deviceId,
1792 .type = DEVICE_ADDED,
1793 });
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001794
1795 // Try to find a matching video device by comparing device names
1796 for (auto it = mUnattachedVideoDevices.begin(); it != mUnattachedVideoDevices.end();
1797 it++) {
1798 std::unique_ptr<TouchVideoDevice>& videoDevice = *it;
Chris Yed3fef462021-03-07 17:10:08 -08001799 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05001800 // videoDevice was transferred to 'device'
1801 it = mUnattachedVideoDevices.erase(it);
1802 break;
1803 }
1804 }
1805
1806 auto [dev_it, inserted] = mDevices.insert_or_assign(device->id, std::move(device));
1807 if (!inserted) {
Chris Ye989bb932020-07-04 16:18:59 -07001808 ALOGW("Device id %d exists, replaced.", device->id);
1809 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001810 mNeedToSendFinishedDeviceScan = true;
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001811 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001812 break;
1813 }
1814 }
1815
1816 if (mNeedToSendFinishedDeviceScan) {
1817 mNeedToSendFinishedDeviceScan = false;
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001818 events.push_back({
1819 .when = now,
1820 .type = FINISHED_DEVICE_SCAN,
1821 });
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001822 if (events.size() == EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001823 break;
1824 }
1825 }
1826
1827 // Grab the next input event.
1828 bool deviceChanged = false;
1829 while (mPendingEventIndex < mPendingEventCount) {
1830 const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001831 if (eventItem.data.fd == mINotifyFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001832 if (eventItem.events & EPOLLIN) {
1833 mPendingINotify = true;
1834 } else {
1835 ALOGW("Received unexpected epoll event 0x%08x for INotify.", eventItem.events);
1836 }
1837 continue;
1838 }
1839
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001840 if (eventItem.data.fd == mWakeReadPipeFd) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 if (eventItem.events & EPOLLIN) {
1842 ALOGV("awoken after wake()");
1843 awoken = true;
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001844 char wakeReadBuffer[16];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 ssize_t nRead;
1846 do {
Siarhei Vishniakoub4d960d2019-10-03 15:38:44 -05001847 nRead = read(mWakeReadPipeFd, wakeReadBuffer, sizeof(wakeReadBuffer));
1848 } while ((nRead == -1 && errno == EINTR) || nRead == sizeof(wakeReadBuffer));
Michael Wrightd02c5b62014-02-10 15:10:22 -08001849 } else {
1850 ALOGW("Received unexpected epoll event 0x%08x for wake read pipe.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001851 eventItem.events);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001852 }
1853 continue;
1854 }
1855
Siarhei Vishniakou4bc561c2018-11-02 17:41:58 -07001856 Device* device = getDeviceByFdLocked(eventItem.data.fd);
Chris Ye989bb932020-07-04 16:18:59 -07001857 if (device == nullptr) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001858 ALOGE("Received unexpected epoll event 0x%08x for unknown fd %d.", eventItem.events,
1859 eventItem.data.fd);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001860 ALOG_ASSERT(!DEBUG);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 continue;
1862 }
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001863 if (device->videoDevice && eventItem.data.fd == device->videoDevice->getFd()) {
1864 if (eventItem.events & EPOLLIN) {
1865 size_t numFrames = device->videoDevice->readAndQueueFrames();
1866 if (numFrames == 0) {
1867 ALOGE("Received epoll event for video device %s, but could not read frame",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001868 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001869 }
1870 } else if (eventItem.events & EPOLLHUP) {
1871 // TODO(b/121395353) - consider adding EPOLLRDHUP
1872 ALOGI("Removing video device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001873 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001874 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
1875 device->videoDevice = nullptr;
1876 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001877 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1878 device->videoDevice->getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07001879 ALOG_ASSERT(!DEBUG);
1880 }
1881 continue;
1882 }
1883 // This must be an input event
Michael Wrightd02c5b62014-02-10 15:10:22 -08001884 if (eventItem.events & EPOLLIN) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001885 int32_t readSize =
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001886 read(device->fd, readBuffer.data(),
1887 sizeof(decltype(readBuffer)::value_type) * readBuffer.size());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001888 if (readSize == 0 || (readSize < 0 && errno == ENODEV)) {
1889 // Device was removed before INotify noticed.
Mark Salyzyn5aa26b22014-06-10 13:07:44 -07001890 ALOGW("could not get event, removed? (fd: %d size: %" PRId32
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001891 " capacity: %zu errno: %d)\n",
1892 device->fd, readSize, readBuffer.size(), errno);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001893 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001894 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001895 } else if (readSize < 0) {
1896 if (errno != EAGAIN && errno != EINTR) {
1897 ALOGW("could not get event (errno=%d)", errno);
1898 }
1899 } else if ((readSize % sizeof(struct input_event)) != 0) {
1900 ALOGE("could not get event (wrong size: %d)", readSize);
1901 } else {
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001902 const int32_t deviceId = device->id == mBuiltInKeyboardId ? 0 : device->id;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001904 const size_t count = size_t(readSize) / sizeof(struct input_event);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001905 for (size_t i = 0; i < count; i++) {
1906 struct input_event& iev = readBuffer[i];
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001907 events.push_back({
1908 .when = processEventTimestamp(iev),
1909 .readTime = systemTime(SYSTEM_TIME_MONOTONIC),
1910 .deviceId = deviceId,
1911 .type = iev.type,
1912 .code = iev.code,
1913 .value = iev.value,
1914 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08001915 }
Siarhei Vishniakou45fd9042022-09-27 13:26:20 -07001916 if (events.size() >= EVENT_BUFFER_SIZE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001917 // The result buffer is full. Reset the pending event index
1918 // so we will try to read the device again on the next iteration.
1919 mPendingEventIndex -= 1;
1920 break;
1921 }
1922 }
1923 } else if (eventItem.events & EPOLLHUP) {
1924 ALOGI("Removing device %s due to epoll hang-up event.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001925 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926 deviceChanged = true;
Chris Ye989bb932020-07-04 16:18:59 -07001927 closeDeviceLocked(*device);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001928 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001929 ALOGW("Received unexpected epoll event 0x%08x for device %s.", eventItem.events,
1930 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001931 }
1932 }
1933
1934 // readNotify() will modify the list of devices so this must be done after
1935 // processing all other events to ensure that we read all remaining events
1936 // before closing the devices.
1937 if (mPendingINotify && mPendingEventIndex >= mPendingEventCount) {
1938 mPendingINotify = false;
Prabir Pradhan952e65b2022-06-23 17:49:55 +00001939 const auto res = readNotifyLocked();
1940 if (!res.ok()) {
1941 ALOGW("Failed to read from inotify: %s", res.error().message().c_str());
1942 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943 deviceChanged = true;
1944 }
1945
1946 // Report added or removed devices immediately.
1947 if (deviceChanged) {
1948 continue;
1949 }
1950
1951 // Return now if we have collected any events or if we were explicitly awoken.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001952 if (!events.empty() || awoken) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953 break;
1954 }
1955
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001956 // Poll for events.
1957 // When a device driver has pending (unread) events, it acquires
1958 // a kernel wake lock. Once the last pending event has been read, the device
1959 // driver will release the kernel wake lock, but the epoll will hold the wakelock,
1960 // since we are using EPOLLWAKEUP. The wakelock is released by the epoll when epoll_wait
1961 // is called again for the same fd that produced the event.
1962 // Thus the system can only sleep if there are no events pending or
1963 // currently being processed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964 //
1965 // The timeout is advisory only. If the device is asleep, it will not wake just to
1966 // service the timeout.
1967 mPendingEventIndex = 0;
1968
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001969 mLock.unlock(); // release lock before poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
1971 int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
1972
Siarhei Vishniakou4b5a87f2019-09-24 13:03:58 +01001973 mLock.lock(); // reacquire lock after poll
Michael Wrightd02c5b62014-02-10 15:10:22 -08001974
1975 if (pollResult == 0) {
1976 // Timed out.
1977 mPendingEventCount = 0;
1978 break;
1979 }
1980
1981 if (pollResult < 0) {
1982 // An error occurred.
1983 mPendingEventCount = 0;
1984
1985 // Sleep after errors to avoid locking up the system.
1986 // Hopefully the error is transient.
1987 if (errno != EINTR) {
1988 ALOGW("poll failed (errno=%d)\n", errno);
1989 usleep(100000);
1990 }
1991 } else {
1992 // Some events occurred.
1993 mPendingEventCount = size_t(pollResult);
1994 }
1995 }
1996
1997 // All done, return the number of events we read.
Siarhei Vishniakou7b3ea0b2022-09-16 14:23:20 -07001998 return events;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999}
2000
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002001std::vector<TouchVideoFrame> EventHub::getVideoFrames(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002002 std::scoped_lock _l(mLock);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002003
2004 Device* device = getDeviceLocked(deviceId);
Chris Ye66fbac32020-07-06 20:36:43 -07002005 if (device == nullptr || !device->videoDevice) {
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08002006 return {};
2007 }
2008 return device->videoDevice->consumeFrames();
2009}
2010
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011void EventHub::wake() {
2012 ALOGV("wake() called");
2013
2014 ssize_t nWrite;
2015 do {
2016 nWrite = write(mWakeWritePipeFd, "W", 1);
2017 } while (nWrite == -1 && errno == EINTR);
2018
2019 if (nWrite != 1 && errno != EAGAIN) {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002020 ALOGW("Could not write wake signal: %s", strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021 }
2022}
2023
2024void EventHub::scanDevicesLocked() {
Usama Arifb27c8e62021-06-03 16:44:09 +01002025 status_t result;
2026 std::error_code errorCode;
2027
2028 if (std::filesystem::exists(DEVICE_INPUT_PATH, errorCode)) {
2029 result = scanDirLocked(DEVICE_INPUT_PATH);
2030 if (result < 0) {
2031 ALOGE("scan dir failed for %s", DEVICE_INPUT_PATH);
2032 }
2033 } else {
2034 if (errorCode) {
2035 ALOGW("Could not run filesystem::exists() due to error %d : %s.", errorCode.value(),
2036 errorCode.message().c_str());
2037 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002038 }
Philip Quinn39b81682019-01-09 22:20:39 -08002039 if (isV4lScanningEnabled()) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002040 result = scanVideoDirLocked(DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002041 if (result != OK) {
Usama Arifb27c8e62021-06-03 16:44:09 +01002042 ALOGE("scan video dir failed for %s", DEVICE_PATH);
Philip Quinn39b81682019-01-09 22:20:39 -08002043 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 }
Chris Ye989bb932020-07-04 16:18:59 -07002045 if (mDevices.find(ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID) == mDevices.end()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 createVirtualKeyboardLocked();
2047 }
2048}
2049
2050// ----------------------------------------------------------------------------
2051
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052static const int32_t GAMEPAD_KEYCODES[] = {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002053 AKEYCODE_BUTTON_A, AKEYCODE_BUTTON_B, AKEYCODE_BUTTON_C, //
2054 AKEYCODE_BUTTON_X, AKEYCODE_BUTTON_Y, AKEYCODE_BUTTON_Z, //
2055 AKEYCODE_BUTTON_L1, AKEYCODE_BUTTON_R1, //
2056 AKEYCODE_BUTTON_L2, AKEYCODE_BUTTON_R2, //
2057 AKEYCODE_BUTTON_THUMBL, AKEYCODE_BUTTON_THUMBR, //
2058 AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE, //
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059};
2060
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002061status_t EventHub::registerFdForEpoll(int fd) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002062 // TODO(b/121395353) - consider adding EPOLLRDHUP
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002063 struct epoll_event eventItem = {};
2064 eventItem.events = EPOLLIN | EPOLLWAKEUP;
2065 eventItem.data.fd = fd;
2066 if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
2067 ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002068 return -errno;
2069 }
2070 return OK;
2071}
2072
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002073status_t EventHub::unregisterFdFromEpoll(int fd) {
2074 if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
2075 ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
2076 return -errno;
2077 }
2078 return OK;
2079}
2080
Chris Ye989bb932020-07-04 16:18:59 -07002081status_t EventHub::registerDeviceForEpollLocked(Device& device) {
2082 status_t result = registerFdForEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002083 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002084 ALOGE("Could not add input device fd to epoll for device %" PRId32, device.id);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002085 return result;
2086 }
Chris Ye989bb932020-07-04 16:18:59 -07002087 if (device.videoDevice) {
2088 registerVideoDeviceForEpollLocked(*device.videoDevice);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002089 }
2090 return result;
2091}
2092
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002093void EventHub::registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) {
2094 status_t result = registerFdForEpoll(videoDevice.getFd());
2095 if (result != OK) {
2096 ALOGE("Could not add video device %s to epoll", videoDevice.getName().c_str());
2097 }
2098}
2099
Chris Ye989bb932020-07-04 16:18:59 -07002100status_t EventHub::unregisterDeviceFromEpollLocked(Device& device) {
2101 if (device.hasValidFd()) {
2102 status_t result = unregisterFdFromEpoll(device.fd);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002103 if (result != OK) {
Chris Ye989bb932020-07-04 16:18:59 -07002104 ALOGW("Could not remove input device fd from epoll for device %" PRId32, device.id);
Siarhei Vishniakou25920312018-12-12 15:24:44 -08002105 return result;
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002106 }
2107 }
Chris Ye989bb932020-07-04 16:18:59 -07002108 if (device.videoDevice) {
2109 unregisterVideoDeviceFromEpollLocked(*device.videoDevice);
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002110 }
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002111 return OK;
2112}
2113
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002114void EventHub::unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) {
2115 if (videoDevice.hasValidFd()) {
2116 status_t result = unregisterFdFromEpoll(videoDevice.getFd());
2117 if (result != OK) {
2118 ALOGW("Could not remove video device fd from epoll for device: %s",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002119 videoDevice.getName().c_str());
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002120 }
2121 }
2122}
2123
Chris Yed3fef462021-03-07 17:10:08 -08002124void EventHub::reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier,
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002125 ftl::Flags<InputDeviceClass> classes) {
Chris Ye657c2f02021-05-25 16:24:37 -07002126 SHA256_CTX ctx;
2127 SHA256_Init(&ctx);
2128 SHA256_Update(&ctx, reinterpret_cast<const uint8_t*>(identifier.uniqueId.c_str()),
2129 identifier.uniqueId.size());
2130 std::array<uint8_t, SHA256_DIGEST_LENGTH> digest;
2131 SHA256_Final(digest.data(), &ctx);
2132
2133 std::string obfuscatedId;
2134 for (size_t i = 0; i < OBFUSCATED_LENGTH; i++) {
2135 obfuscatedId += StringPrintf("%02x", digest[i]);
2136 }
2137
Chris Yed3fef462021-03-07 17:10:08 -08002138 android::util::stats_write(android::util::INPUTDEVICE_REGISTERED, identifier.name.c_str(),
2139 identifier.vendor, identifier.product, identifier.version,
Chris Ye657c2f02021-05-25 16:24:37 -07002140 identifier.bus, obfuscatedId.c_str(), classes.get());
Chris Yed3fef462021-03-07 17:10:08 -08002141}
2142
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002143void EventHub::openDeviceLocked(const std::string& devicePath) {
2144 // If an input device happens to register around the time when EventHub's constructor runs, it
2145 // is possible that the same input event node (for example, /dev/input/event3) will be noticed
2146 // in both 'inotify' callback and also in the 'scanDirLocked' pass. To prevent duplicate devices
2147 // from getting registered, ensure that this path is not already covered by an existing device.
2148 for (const auto& [deviceId, device] : mDevices) {
2149 if (device->path == devicePath) {
2150 return; // device was already registered
2151 }
2152 }
2153
Michael Wrightd02c5b62014-02-10 15:10:22 -08002154 char buffer[80];
2155
Chris Ye8594e192020-07-14 10:34:06 -07002156 ALOGV("Opening device: %s", devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157
Chris Ye8594e192020-07-14 10:34:06 -07002158 int fd = open(devicePath.c_str(), O_RDWR | O_CLOEXEC | O_NONBLOCK);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002159 if (fd < 0) {
Chris Ye8594e192020-07-14 10:34:06 -07002160 ALOGE("could not open %s, %s\n", devicePath.c_str(), strerror(errno));
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002161 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002162 }
2163
2164 InputDeviceIdentifier identifier;
2165
2166 // Get device name.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002167 if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
Chris Ye8594e192020-07-14 10:34:06 -07002168 ALOGE("Could not get device name for %s: %s", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002169 } else {
2170 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002171 identifier.name = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002172 }
2173
2174 // Check to see if the device is on our excluded list
2175 for (size_t i = 0; i < mExcludedDevices.size(); i++) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002176 const std::string& item = mExcludedDevices[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002177 if (identifier.name == item) {
Chris Ye8594e192020-07-14 10:34:06 -07002178 ALOGI("ignoring event id %s driver %s\n", devicePath.c_str(), item.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002180 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002181 }
2182 }
2183
2184 // Get device driver version.
2185 int driverVersion;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002186 if (ioctl(fd, EVIOCGVERSION, &driverVersion)) {
Chris Ye8594e192020-07-14 10:34:06 -07002187 ALOGE("could not get driver version for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002189 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190 }
2191
2192 // Get device identifier.
2193 struct input_id inputId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002194 if (ioctl(fd, EVIOCGID, &inputId)) {
Chris Ye8594e192020-07-14 10:34:06 -07002195 ALOGE("could not get device input id for %s, %s\n", devicePath.c_str(), strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196 close(fd);
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002197 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198 }
2199 identifier.bus = inputId.bustype;
2200 identifier.product = inputId.product;
2201 identifier.vendor = inputId.vendor;
2202 identifier.version = inputId.version;
2203
2204 // Get device physical location.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002205 if (ioctl(fd, EVIOCGPHYS(sizeof(buffer) - 1), &buffer) < 1) {
2206 // fprintf(stderr, "could not get location for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 } else {
2208 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002209 identifier.location = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 }
2211
2212 // Get device unique id.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002213 if (ioctl(fd, EVIOCGUNIQ(sizeof(buffer) - 1), &buffer) < 1) {
2214 // fprintf(stderr, "could not get idstring for %s, %s\n", devicePath, strerror(errno));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215 } else {
2216 buffer[sizeof(buffer) - 1] = '\0';
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002217 identifier.uniqueId = buffer;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218 }
2219
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002220 // Attempt to get the bluetooth address of an input device from the uniqueId.
2221 if (identifier.bus == BUS_BLUETOOTH &&
2222 std::regex_match(identifier.uniqueId,
2223 std::regex("^[A-Fa-f0-9]{2}(?::[A-Fa-f0-9]{2}){5}$"))) {
2224 identifier.bluetoothAddress = identifier.uniqueId;
2225 // The Bluetooth stack requires alphabetic characters to be uppercase in a valid address.
2226 for (auto& c : *identifier.bluetoothAddress) {
2227 c = ::toupper(c);
2228 }
2229 }
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 // Fill in the descriptor.
2232 assignDescriptorLocked(identifier);
2233
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 // Allocate device. (The device object takes ownership of the fd at this point.)
2235 int32_t deviceId = mNextDeviceId++;
Prabir Pradhancb42b472022-08-23 16:01:19 +00002236 std::unique_ptr<Device> device =
2237 std::make_unique<Device>(fd, deviceId, devicePath, identifier,
2238 obtainAssociatedDeviceLocked(devicePath));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239
Chris Ye8594e192020-07-14 10:34:06 -07002240 ALOGV("add device %d: %s\n", deviceId, devicePath.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241 ALOGV(" bus: %04x\n"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002242 " vendor %04x\n"
2243 " product %04x\n"
2244 " version %04x\n",
2245 identifier.bus, identifier.vendor, identifier.product, identifier.version);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002246 ALOGV(" name: \"%s\"\n", identifier.name.c_str());
2247 ALOGV(" location: \"%s\"\n", identifier.location.c_str());
2248 ALOGV(" unique id: \"%s\"\n", identifier.uniqueId.c_str());
2249 ALOGV(" descriptor: \"%s\"\n", identifier.descriptor.c_str());
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002250 ALOGV(" driver: v%d.%d.%d\n", driverVersion >> 16, (driverVersion >> 8) & 0xff,
2251 driverVersion & 0xff);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252
2253 // Load the configuration file for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002254 device->loadConfigurationLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002255
2256 // Figure out the kinds of events the device reports.
Chris Ye66fbac32020-07-06 20:36:43 -07002257 device->readDeviceBitMask(EVIOCGBIT(EV_KEY, 0), device->keyBitmask);
2258 device->readDeviceBitMask(EVIOCGBIT(EV_ABS, 0), device->absBitmask);
2259 device->readDeviceBitMask(EVIOCGBIT(EV_REL, 0), device->relBitmask);
2260 device->readDeviceBitMask(EVIOCGBIT(EV_SW, 0), device->swBitmask);
2261 device->readDeviceBitMask(EVIOCGBIT(EV_LED, 0), device->ledBitmask);
2262 device->readDeviceBitMask(EVIOCGBIT(EV_FF, 0), device->ffBitmask);
Chris Yef59a2f42020-10-16 12:55:26 -07002263 device->readDeviceBitMask(EVIOCGBIT(EV_MSC, 0), device->mscBitmask);
Chris Ye66fbac32020-07-06 20:36:43 -07002264 device->readDeviceBitMask(EVIOCGPROP(0), device->propBitmask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002266 // See if this is a device with keys. This could be full keyboard, or other devices like
2267 // gamepads, joysticks, and styluses with buttons that should generate key presses.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002268 bool haveKeyboardKeys =
Chris Ye66fbac32020-07-06 20:36:43 -07002269 device->keyBitmask.any(0, BTN_MISC) || device->keyBitmask.any(BTN_WHEEL, KEY_MAX + 1);
2270 bool haveGamepadButtons = device->keyBitmask.any(BTN_MISC, BTN_MOUSE) ||
2271 device->keyBitmask.any(BTN_JOYSTICK, BTN_DIGI);
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002272 bool haveStylusButtons = device->keyBitmask.test(BTN_STYLUS) ||
2273 device->keyBitmask.test(BTN_STYLUS2) || device->keyBitmask.test(BTN_STYLUS3);
2274 if (haveKeyboardKeys || haveGamepadButtons || haveStylusButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002275 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276 }
2277
2278 // See if this is a cursor device such as a trackball or mouse.
Chris Ye66fbac32020-07-06 20:36:43 -07002279 if (device->keyBitmask.test(BTN_MOUSE) && device->relBitmask.test(REL_X) &&
2280 device->relBitmask.test(REL_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002281 device->classes |= InputDeviceClass::CURSOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282 }
2283
Prabir Pradhana3621852022-10-14 18:57:23 +00002284 // See if the device is specially configured to be of a certain type.
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07002285 std::string deviceType;
2286 if (device->configuration && device->configuration->tryGetProperty("device.type", deviceType)) {
2287 if (deviceType == "rotaryEncoder") {
Chris Ye1b0c7342020-07-28 21:57:03 -07002288 device->classes |= InputDeviceClass::ROTARY_ENCODER;
Prabir Pradhana3621852022-10-14 18:57:23 +00002289 } else if (deviceType == "externalStylus") {
2290 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002291 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002292 }
2293
Michael Wrightd02c5b62014-02-10 15:10:22 -08002294 // See if this is a touch pad.
2295 // Is this a new modern multi-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002296 if (device->absBitmask.test(ABS_MT_POSITION_X) && device->absBitmask.test(ABS_MT_POSITION_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 // Some joysticks such as the PS3 controller report axes that conflict
2298 // with the ABS_MT range. Try to confirm that the device really is
2299 // a touch screen.
Chris Ye66fbac32020-07-06 20:36:43 -07002300 if (device->keyBitmask.test(BTN_TOUCH) || !haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002301 device->classes |= (InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT);
Harry Cutts79cc9fa2022-10-28 15:32:39 +00002302 if (device->propBitmask.test(INPUT_PROP_POINTER) &&
2303 !device->keyBitmask.any(BTN_TOOL_PEN, BTN_TOOL_FINGER) && !haveStylusButtons) {
2304 device->classes |= InputDeviceClass::TOUCHPAD;
2305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002307 // Is this an old style single-touch driver?
Chris Ye66fbac32020-07-06 20:36:43 -07002308 } else if (device->keyBitmask.test(BTN_TOUCH) && device->absBitmask.test(ABS_X) &&
2309 device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002310 device->classes |= InputDeviceClass::TOUCH;
Prabir Pradhane1a41a82022-10-14 18:06:50 +00002311 // Is this a stylus that reports contact/pressure independently of touch coordinates?
Chris Ye66fbac32020-07-06 20:36:43 -07002312 } else if ((device->absBitmask.test(ABS_PRESSURE) || device->keyBitmask.test(BTN_TOUCH)) &&
2313 !device->absBitmask.test(ABS_X) && !device->absBitmask.test(ABS_Y)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002314 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002315 }
2316
2317 // See if this device is a joystick.
2318 // Assumes that joysticks always have gamepad buttons in order to distinguish them
2319 // from other devices such as accelerometers that also have absolute axes.
2320 if (haveGamepadButtons) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002321 auto assumedClasses = device->classes | InputDeviceClass::JOYSTICK;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002322 for (int i = 0; i <= ABS_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002323 if (device->absBitmask.test(i) &&
Chris Ye1b0c7342020-07-28 21:57:03 -07002324 (getAbsAxisUsage(i, assumedClasses).test(InputDeviceClass::JOYSTICK))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 device->classes = assumedClasses;
2326 break;
2327 }
2328 }
2329 }
2330
Chris Yef59a2f42020-10-16 12:55:26 -07002331 // Check whether this device is an accelerometer.
2332 if (device->propBitmask.test(INPUT_PROP_ACCELEROMETER)) {
2333 device->classes |= InputDeviceClass::SENSOR;
2334 }
2335
Michael Wrightd02c5b62014-02-10 15:10:22 -08002336 // Check whether this device has switches.
2337 for (int i = 0; i <= SW_MAX; i++) {
Chris Ye66fbac32020-07-06 20:36:43 -07002338 if (device->swBitmask.test(i)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002339 device->classes |= InputDeviceClass::SWITCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002340 break;
2341 }
2342 }
2343
2344 // Check whether this device supports the vibrator.
Chris Ye66fbac32020-07-06 20:36:43 -07002345 if (device->ffBitmask.test(FF_RUMBLE)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002346 device->classes |= InputDeviceClass::VIBRATOR;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002347 }
2348
2349 // Configure virtual keys.
Chris Ye1b0c7342020-07-28 21:57:03 -07002350 if ((device->classes.test(InputDeviceClass::TOUCH))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002351 // Load the virtual keys for the touch screen, if any.
2352 // We do this now so that we can make sure to load the keymap if necessary.
Chris Ye989bb932020-07-04 16:18:59 -07002353 bool success = device->loadVirtualKeyMapLocked();
Siarhei Vishniakou3e78dec2019-02-20 16:21:46 -06002354 if (success) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002355 device->classes |= InputDeviceClass::KEYBOARD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357 }
2358
2359 // Load the key map.
Chris Yef59a2f42020-10-16 12:55:26 -07002360 // We need to do this for joysticks too because the key layout may specify axes, and for
2361 // sensor as well because the key layout may specify the axes to sensor data mapping.
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 status_t keyMapStatus = NAME_NOT_FOUND;
Chris Yef59a2f42020-10-16 12:55:26 -07002363 if (device->classes.any(InputDeviceClass::KEYBOARD | InputDeviceClass::JOYSTICK |
2364 InputDeviceClass::SENSOR)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002365 // Load the keymap for the device.
Chris Ye989bb932020-07-04 16:18:59 -07002366 keyMapStatus = device->loadKeyMapLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002367 }
2368
2369 // Configure the keyboard, gamepad or virtual keyboard.
Chris Ye1b0c7342020-07-28 21:57:03 -07002370 if (device->classes.test(InputDeviceClass::KEYBOARD)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371 // Register the keyboard as a built-in keyboard if it is eligible.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002372 if (!keyMapStatus && mBuiltInKeyboardId == NO_BUILT_IN_KEYBOARD &&
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002373 isEligibleBuiltInKeyboard(device->identifier, device->configuration.get(),
2374 &device->keyMap)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 mBuiltInKeyboardId = device->id;
2376 }
2377
2378 // 'Q' key support = cheap test of whether this is an alpha-capable kbd
Chris Ye989bb932020-07-04 16:18:59 -07002379 if (device->hasKeycodeLocked(AKEYCODE_Q)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002380 device->classes |= InputDeviceClass::ALPHAKEY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 }
2382
2383 // See if this device has a DPAD.
Chris Ye989bb932020-07-04 16:18:59 -07002384 if (device->hasKeycodeLocked(AKEYCODE_DPAD_UP) &&
2385 device->hasKeycodeLocked(AKEYCODE_DPAD_DOWN) &&
2386 device->hasKeycodeLocked(AKEYCODE_DPAD_LEFT) &&
2387 device->hasKeycodeLocked(AKEYCODE_DPAD_RIGHT) &&
2388 device->hasKeycodeLocked(AKEYCODE_DPAD_CENTER)) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002389 device->classes |= InputDeviceClass::DPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002390 }
2391
2392 // See if this device has a gamepad.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002393 for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES) / sizeof(GAMEPAD_KEYCODES[0]); i++) {
Chris Ye989bb932020-07-04 16:18:59 -07002394 if (device->hasKeycodeLocked(GAMEPAD_KEYCODES[i])) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002395 device->classes |= InputDeviceClass::GAMEPAD;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 break;
2397 }
2398 }
Prabir Pradhana3621852022-10-14 18:57:23 +00002399
2400 // See if this device has any stylus buttons that we would want to fuse with touch data.
2401 if (!device->classes.any(InputDeviceClass::TOUCH | InputDeviceClass::TOUCH_MT)) {
2402 for (int32_t keycode : STYLUS_BUTTON_KEYCODES) {
2403 if (device->hasKeycodeLocked(keycode)) {
2404 device->classes |= InputDeviceClass::EXTERNAL_STYLUS;
2405 break;
2406 }
2407 }
2408 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
2411 // If the device isn't recognized as something we handle, don't monitor it.
Dominik Laskowski2f01d772022-03-23 16:01:29 -07002412 if (device->classes == ftl::Flags<InputDeviceClass>(0)) {
Chris Ye8594e192020-07-14 10:34:06 -07002413 ALOGV("Dropping device: id=%d, path='%s', name='%s'", deviceId, devicePath.c_str(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002414 device->identifier.name.c_str());
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002415 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002416 }
2417
Chris Ye3fdbfef2021-01-06 18:45:18 -08002418 // Classify InputDeviceClass::BATTERY.
Prabir Pradhan51894782022-08-23 16:29:10 +00002419 if (device->associatedDevice && !device->associatedDevice->batteryInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002420 device->classes |= InputDeviceClass::BATTERY;
2421 }
Kim Low03ea0352020-11-06 12:45:07 -08002422
Chris Ye3fdbfef2021-01-06 18:45:18 -08002423 // Classify InputDeviceClass::LIGHT.
Prabir Pradhan51894782022-08-23 16:29:10 +00002424 if (device->associatedDevice && !device->associatedDevice->lightInfos.empty()) {
Chris Ye3fdbfef2021-01-06 18:45:18 -08002425 device->classes |= InputDeviceClass::LIGHT;
Kim Low03ea0352020-11-06 12:45:07 -08002426 }
2427
Tim Kilbourn063ff532015-04-08 10:26:18 -07002428 // Determine whether the device has a mic.
Chris Ye989bb932020-07-04 16:18:59 -07002429 if (device->deviceHasMicLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002430 device->classes |= InputDeviceClass::MIC;
Tim Kilbourn063ff532015-04-08 10:26:18 -07002431 }
2432
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 // Determine whether the device is external or internal.
Chris Ye989bb932020-07-04 16:18:59 -07002434 if (device->isExternalDeviceLocked()) {
Chris Ye1b0c7342020-07-28 21:57:03 -07002435 device->classes |= InputDeviceClass::EXTERNAL;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002436 }
2437
Chris Ye1b0c7342020-07-28 21:57:03 -07002438 if (device->classes.any(InputDeviceClass::JOYSTICK | InputDeviceClass::DPAD) &&
2439 device->classes.test(InputDeviceClass::GAMEPAD)) {
Chris Ye989bb932020-07-04 16:18:59 -07002440 device->controllerNumber = getNextControllerNumberLocked(device->identifier.name);
2441 device->setLedForControllerLocked();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 }
2443
Chris Ye989bb932020-07-04 16:18:59 -07002444 if (registerDeviceForEpollLocked(*device) != OK) {
Siarhei Vishniakoua4c502a2021-02-05 00:45:20 +00002445 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002446 }
2447
Chris Ye989bb932020-07-04 16:18:59 -07002448 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002449
Chris Ye1b0c7342020-07-28 21:57:03 -07002450 ALOGI("New device: id=%d, fd=%d, path='%s', name='%s', classes=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002451 "configuration='%s', keyLayout='%s', keyCharacterMap='%s', builtinKeyboard=%s, ",
Chris Ye1b0c7342020-07-28 21:57:03 -07002452 deviceId, fd, devicePath.c_str(), device->identifier.name.c_str(),
2453 device->classes.string().c_str(), device->configurationFile.c_str(),
2454 device->keyMap.keyLayoutFile.c_str(), device->keyMap.keyCharacterMapFile.c_str(),
2455 toString(mBuiltInKeyboardId == deviceId));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002456
Chris Ye989bb932020-07-04 16:18:59 -07002457 addDeviceLocked(std::move(device));
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002458}
2459
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002460void EventHub::openVideoDeviceLocked(const std::string& devicePath) {
2461 std::unique_ptr<TouchVideoDevice> videoDevice = TouchVideoDevice::create(devicePath);
2462 if (!videoDevice) {
2463 ALOGE("Could not create touch video device for %s. Ignoring", devicePath.c_str());
2464 return;
2465 }
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002466 // Transfer ownership of this video device to a matching input device
Chris Ye989bb932020-07-04 16:18:59 -07002467 for (const auto& [id, device] : mDevices) {
Chris Yed3fef462021-03-07 17:10:08 -08002468 if (tryAddVideoDeviceLocked(*device, videoDevice)) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002469 return; // 'device' now owns 'videoDevice'
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002470 }
2471 }
2472
2473 // Couldn't find a matching input device, so just add it to a temporary holding queue.
2474 // A matching input device may appear later.
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002475 ALOGI("Adding video device %s to list of unattached video devices",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002476 videoDevice->getName().c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002477 mUnattachedVideoDevices.push_back(std::move(videoDevice));
2478}
2479
Chris Yed3fef462021-03-07 17:10:08 -08002480bool EventHub::tryAddVideoDeviceLocked(EventHub::Device& device,
2481 std::unique_ptr<TouchVideoDevice>& videoDevice) {
Siarhei Vishniakouf49608d2020-08-20 19:18:21 -05002482 if (videoDevice->getName() != device.identifier.name) {
2483 return false;
2484 }
2485 device.videoDevice = std::move(videoDevice);
2486 if (device.enabled) {
2487 registerVideoDeviceForEpollLocked(*device.videoDevice);
2488 }
2489 return true;
2490}
2491
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002492bool EventHub::isDeviceEnabled(int32_t deviceId) const {
Chris Ye87143712020-11-10 05:05:58 +00002493 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002494 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002495 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002496 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2497 return false;
2498 }
2499 return device->enabled;
2500}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002501
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002502status_t EventHub::enableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002503 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002504 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002505 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002506 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2507 return BAD_VALUE;
2508 }
2509 if (device->enabled) {
2510 ALOGW("Duplicate call to %s, input device %" PRId32 " already enabled", __func__, deviceId);
2511 return OK;
2512 }
2513 status_t result = device->enable();
2514 if (result != OK) {
2515 ALOGE("Failed to enable device %" PRId32, deviceId);
2516 return result;
2517 }
2518
Chris Ye989bb932020-07-04 16:18:59 -07002519 device->configureFd();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002520
Chris Ye989bb932020-07-04 16:18:59 -07002521 return registerDeviceForEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002522}
2523
2524status_t EventHub::disableDevice(int32_t deviceId) {
Chris Ye87143712020-11-10 05:05:58 +00002525 std::scoped_lock _l(mLock);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002526 Device* device = getDeviceLocked(deviceId);
Yi Kong9b14ac62018-07-17 13:48:38 -07002527 if (device == nullptr) {
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002528 ALOGE("Invalid device id=%" PRId32 " provided to %s", deviceId, __func__);
2529 return BAD_VALUE;
2530 }
2531 if (!device->enabled) {
2532 ALOGW("Duplicate call to %s, input device already disabled", __func__);
2533 return OK;
2534 }
Chris Ye989bb932020-07-04 16:18:59 -07002535 unregisterDeviceFromEpollLocked(*device);
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002536 return device->disable();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002537}
2538
2539void EventHub::createVirtualKeyboardLocked() {
2540 InputDeviceIdentifier identifier;
2541 identifier.name = "Virtual";
2542 identifier.uniqueId = "<virtual>";
2543 assignDescriptorLocked(identifier);
2544
Chris Ye989bb932020-07-04 16:18:59 -07002545 std::unique_ptr<Device> device =
2546 std::make_unique<Device>(-1, ReservedInputDeviceId::VIRTUAL_KEYBOARD_ID, "<virtual>",
Harry Cutts33476232023-01-30 19:57:29 +00002547 identifier, /*associatedDevice=*/nullptr);
Chris Ye1b0c7342020-07-28 21:57:03 -07002548 device->classes = InputDeviceClass::KEYBOARD | InputDeviceClass::ALPHAKEY |
2549 InputDeviceClass::DPAD | InputDeviceClass::VIRTUAL;
Chris Ye989bb932020-07-04 16:18:59 -07002550 device->loadKeyMapLocked();
2551 addDeviceLocked(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552}
2553
Chris Ye989bb932020-07-04 16:18:59 -07002554void EventHub::addDeviceLocked(std::unique_ptr<Device> device) {
Chris Yed3fef462021-03-07 17:10:08 -08002555 reportDeviceAddedForStatisticsLocked(device->identifier, device->classes);
Chris Ye989bb932020-07-04 16:18:59 -07002556 mOpeningDevices.push_back(std::move(device));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557}
2558
Chris Ye989bb932020-07-04 16:18:59 -07002559int32_t EventHub::getNextControllerNumberLocked(const std::string& name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 if (mControllerNumbers.isFull()) {
2561 ALOGI("Maximum number of controllers reached, assigning controller number 0 to device %s",
Chris Ye989bb932020-07-04 16:18:59 -07002562 name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 return 0;
2564 }
2565 // Since the controller number 0 is reserved for non-controllers, translate all numbers up by
2566 // one
2567 return static_cast<int32_t>(mControllerNumbers.markFirstUnmarkedBit() + 1);
2568}
2569
Chris Ye989bb932020-07-04 16:18:59 -07002570void EventHub::releaseControllerNumberLocked(int32_t num) {
2571 if (num > 0) {
2572 mControllerNumbers.clearBit(static_cast<uint32_t>(num - 1));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002574}
2575
Chris Ye8594e192020-07-14 10:34:06 -07002576void EventHub::closeDeviceByPathLocked(const std::string& devicePath) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 Device* device = getDeviceByPathLocked(devicePath);
Chris Ye989bb932020-07-04 16:18:59 -07002578 if (device != nullptr) {
2579 closeDeviceLocked(*device);
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002580 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002581 }
Chris Ye8594e192020-07-14 10:34:06 -07002582 ALOGV("Remove device: %s not found, device may already have been removed.", devicePath.c_str());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002583}
2584
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002585/**
2586 * Find the video device by filename, and close it.
2587 * The video device is closed by path during an inotify event, where we don't have the
2588 * additional context about the video device fd, or the associated input device.
2589 */
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002590void EventHub::closeVideoDeviceByPathLocked(const std::string& devicePath) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002591 // A video device may be owned by an existing input device, or it may be stored in
2592 // the mUnattachedVideoDevices queue. Check both locations.
Chris Ye989bb932020-07-04 16:18:59 -07002593 for (const auto& [id, device] : mDevices) {
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002594 if (device->videoDevice && device->videoDevice->getPath() == devicePath) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002595 unregisterVideoDeviceFromEpollLocked(*device->videoDevice);
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002596 device->videoDevice = nullptr;
2597 return;
2598 }
2599 }
Siarhei Vishniakouf47c339e2021-12-30 11:22:26 -08002600 std::erase_if(mUnattachedVideoDevices,
2601 [&devicePath](const std::unique_ptr<TouchVideoDevice>& videoDevice) {
2602 return videoDevice->getPath() == devicePath;
2603 });
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604}
2605
2606void EventHub::closeAllDevicesLocked() {
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002607 mUnattachedVideoDevices.clear();
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002608 while (!mDevices.empty()) {
2609 closeDeviceLocked(*(mDevices.begin()->second));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002610 }
2611}
2612
Chris Ye989bb932020-07-04 16:18:59 -07002613void EventHub::closeDeviceLocked(Device& device) {
2614 ALOGI("Removed device: path=%s name=%s id=%d fd=%d classes=%s", device.path.c_str(),
2615 device.identifier.name.c_str(), device.id, device.fd, device.classes.string().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002616
Chris Ye989bb932020-07-04 16:18:59 -07002617 if (device.id == mBuiltInKeyboardId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002618 ALOGW("built-in keyboard device %s (id=%d) is closing! the apps will not like this",
Chris Ye989bb932020-07-04 16:18:59 -07002619 device.path.c_str(), mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 mBuiltInKeyboardId = NO_BUILT_IN_KEYBOARD;
2621 }
2622
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07002623 unregisterDeviceFromEpollLocked(device);
Chris Ye989bb932020-07-04 16:18:59 -07002624 if (device.videoDevice) {
Siarhei Vishniakou12598682018-11-02 17:19:19 -07002625 // This must be done after the video device is removed from epoll
Chris Ye989bb932020-07-04 16:18:59 -07002626 mUnattachedVideoDevices.push_back(std::move(device.videoDevice));
Siarhei Vishniakouec7854a2018-12-14 16:52:34 -08002627 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002628
Chris Ye989bb932020-07-04 16:18:59 -07002629 releaseControllerNumberLocked(device.controllerNumber);
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002630 device.controllerNumber = 0;
Chris Ye989bb932020-07-04 16:18:59 -07002631 device.close();
Chris Ye989bb932020-07-04 16:18:59 -07002632 mClosingDevices.push_back(std::move(mDevices[device.id]));
Siarhei Vishniakoud549b252020-08-11 11:25:26 -05002633
Chris Ye989bb932020-07-04 16:18:59 -07002634 mDevices.erase(device.id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002635}
2636
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002637base::Result<void> EventHub::readNotifyLocked() {
2638 static constexpr auto EVENT_SIZE = static_cast<ssize_t>(sizeof(inotify_event));
2639 uint8_t eventBuffer[512];
2640 ssize_t sizeRead;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641
2642 ALOGV("EventHub::readNotify nfd: %d\n", mINotifyFd);
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002643 do {
2644 sizeRead = read(mINotifyFd, eventBuffer, sizeof(eventBuffer));
2645 } while (sizeRead < 0 && errno == EINTR);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002647 if (sizeRead < EVENT_SIZE) return Errorf("could not get event, %s", strerror(errno));
2648
2649 for (ssize_t eventPos = 0; sizeRead >= EVENT_SIZE;) {
2650 const inotify_event* event;
2651 event = (const inotify_event*)(eventBuffer + eventPos);
2652 if (event->len == 0) continue;
2653
2654 handleNotifyEventLocked(*event);
2655
2656 const ssize_t eventSize = EVENT_SIZE + event->len;
2657 sizeRead -= eventSize;
2658 eventPos += eventSize;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002659 }
Prabir Pradhan952e65b2022-06-23 17:49:55 +00002660 return {};
2661}
2662
2663void EventHub::handleNotifyEventLocked(const inotify_event& event) {
2664 if (event.wd == mDeviceInputWd) {
2665 std::string filename = std::string(DEVICE_INPUT_PATH) + "/" + event.name;
2666 if (event.mask & IN_CREATE) {
2667 openDeviceLocked(filename);
2668 } else {
2669 ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
2670 closeDeviceByPathLocked(filename);
2671 }
2672 } else if (event.wd == mDeviceWd) {
2673 if (isV4lTouchNode(event.name)) {
2674 std::string filename = std::string(DEVICE_PATH) + "/" + event.name;
2675 if (event.mask & IN_CREATE) {
2676 openVideoDeviceLocked(filename);
2677 } else {
2678 ALOGI("Removing video device '%s' due to inotify event", filename.c_str());
2679 closeVideoDeviceByPathLocked(filename);
2680 }
2681 } else if (strcmp(event.name, "input") == 0 && event.mask & IN_CREATE) {
2682 addDeviceInputInotify();
2683 }
2684 } else {
2685 LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event.wd);
2686 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687}
2688
Chris Ye8594e192020-07-14 10:34:06 -07002689status_t EventHub::scanDirLocked(const std::string& dirname) {
2690 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2691 openDeviceLocked(entry.path());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002693 return 0;
2694}
2695
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002696/**
2697 * Look for all dirname/v4l-touch* devices, and open them.
2698 */
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002699status_t EventHub::scanVideoDirLocked(const std::string& dirname) {
Chris Ye8594e192020-07-14 10:34:06 -07002700 for (const auto& entry : std::filesystem::directory_iterator(dirname)) {
2701 if (isV4lTouchNode(entry.path())) {
2702 ALOGI("Found touch video device %s", entry.path().c_str());
2703 openVideoDeviceLocked(entry.path());
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002704 }
2705 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002706 return OK;
2707}
2708
Michael Wrightd02c5b62014-02-10 15:10:22 -08002709void EventHub::requestReopenDevices() {
2710 ALOGV("requestReopenDevices() called");
2711
Chris Ye87143712020-11-10 05:05:58 +00002712 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 mNeedToReopenDevices = true;
2714}
2715
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002716void EventHub::dump(std::string& dump) const {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002717 dump += "Event Hub State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002718
2719 { // acquire lock
Chris Ye87143712020-11-10 05:05:58 +00002720 std::scoped_lock _l(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002721
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002722 dump += StringPrintf(INDENT "BuiltInKeyboardId: %d\n", mBuiltInKeyboardId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002723
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002724 dump += INDENT "Devices:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002725
Chris Ye989bb932020-07-04 16:18:59 -07002726 for (const auto& [id, device] : mDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002727 if (mBuiltInKeyboardId == device->id) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002728 dump += StringPrintf(INDENT2 "%d: %s (aka device 0 - built-in keyboard)\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002729 device->id, device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002730 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002731 dump += StringPrintf(INDENT2 "%d: %s\n", device->id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002732 device->identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002733 }
Chris Ye1b0c7342020-07-28 21:57:03 -07002734 dump += StringPrintf(INDENT3 "Classes: %s\n", device->classes.string().c_str());
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002735 dump += StringPrintf(INDENT3 "Path: %s\n", device->path.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002736 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(device->enabled));
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002737 dump += StringPrintf(INDENT3 "Descriptor: %s\n", device->identifier.descriptor.c_str());
2738 dump += StringPrintf(INDENT3 "Location: %s\n", device->identifier.location.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002739 dump += StringPrintf(INDENT3 "ControllerNumber: %d\n", device->controllerNumber);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002740 dump += StringPrintf(INDENT3 "UniqueId: %s\n", device->identifier.uniqueId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002741 dump += StringPrintf(INDENT3 "Identifier: bus=0x%04x, vendor=0x%04x, "
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002742 "product=0x%04x, version=0x%04x, bluetoothAddress=%s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002743 device->identifier.bus, device->identifier.vendor,
Prabir Pradhan07525ef2022-10-03 21:51:26 +00002744 device->identifier.product, device->identifier.version,
2745 toString(device->identifier.bluetoothAddress).c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002746 dump += StringPrintf(INDENT3 "KeyLayoutFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002747 device->keyMap.keyLayoutFile.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002748 dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002749 device->keyMap.keyCharacterMapFile.c_str());
Vaibhav Devmurari7fb41132023-01-02 13:30:26 +00002750 if (device->associatedDevice && device->associatedDevice->layoutInfo) {
2751 dump += StringPrintf(INDENT3 "LanguageTag: %s\n",
2752 device->associatedDevice->layoutInfo->languageTag.c_str());
2753 dump += StringPrintf(INDENT3 "LayoutType: %s\n",
2754 device->associatedDevice->layoutInfo->layoutType.c_str());
2755 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002756 dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002757 device->configurationFile.c_str());
Prabir Pradhan51894782022-08-23 16:29:10 +00002758 dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
2759 device->videoDevice ? device->videoDevice->dump().c_str()
2760 : "<none>");
2761 dump += StringPrintf(INDENT3 "SysfsDevicePath: %s\n",
2762 device->associatedDevice
2763 ? device->associatedDevice->sysfsRootPath.c_str()
2764 : "<none>");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 }
Siarhei Vishniakou22c88462018-12-13 19:34:53 -08002766
2767 dump += INDENT "Unattached video devices:\n";
2768 for (const std::unique_ptr<TouchVideoDevice>& videoDevice : mUnattachedVideoDevices) {
2769 dump += INDENT2 + videoDevice->dump() + "\n";
2770 }
2771 if (mUnattachedVideoDevices.empty()) {
2772 dump += INDENT2 "<none>\n";
2773 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002774 } // release lock
2775}
2776
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002777void EventHub::monitor() const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002778 // Acquire and release the lock to ensure that the event hub has not deadlocked.
Chris Ye1c2e0892020-11-30 21:41:44 -08002779 std::unique_lock<std::mutex> lock(mLock);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780}
2781
Prabir Pradhanedeec3b2022-08-26 22:33:55 +00002782std::string EventHub::AssociatedDevice::dump() const {
2783 return StringPrintf("path=%s, numBatteries=%zu, numLight=%zu", sysfsRootPath.c_str(),
2784 batteryInfos.size(), lightInfos.size());
2785}
2786
Prabir Pradhanae4ff282022-08-23 16:21:39 +00002787} // namespace android