1 /* 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 17 #pragma once 18 19 #include <bitset> 20 #include <climits> 21 #include <filesystem> 22 #include <functional> 23 #include <map> 24 #include <memory> 25 #include <optional> 26 #include <ostream> 27 #include <string> 28 #include <unordered_map> 29 #include <utility> 30 #include <vector> 31 32 #include <batteryservice/BatteryService.h> 33 #include <ftl/flags.h> 34 #include <input/BlockingQueue.h> 35 #include <input/Input.h> 36 #include <input/InputDevice.h> 37 #include <input/KeyCharacterMap.h> 38 #include <input/KeyLayoutMap.h> 39 #include <input/Keyboard.h> 40 #include <input/PropertyMap.h> 41 #include <input/VirtualKeyMap.h> 42 #include <linux/input.h> 43 #include <sys/epoll.h> 44 #include <utils/BitSet.h> 45 #include <utils/Errors.h> 46 #include <utils/List.h> 47 #include <utils/Log.h> 48 #include <utils/Mutex.h> 49 50 #include "TouchVideoDevice.h" 51 #include "VibrationElement.h" 52 53 struct inotify_event; 54 55 namespace android { 56 57 /* Number of colors : {red, green, blue} */ 58 static constexpr size_t COLOR_NUM = 3; 59 /* 60 * A raw event as retrieved from the EventHub. 61 */ 62 struct RawEvent { 63 // Time when the event happened 64 nsecs_t when; 65 // Time when the event was read by EventHub. Only populated for input events. 66 // For other events (device added/removed/etc), this value is undefined and should not be read. 67 nsecs_t readTime; 68 int32_t deviceId; 69 int32_t type; 70 int32_t code; 71 int32_t value; 72 }; 73 74 /* Describes an absolute axis. */ 75 struct RawAbsoluteAxisInfo { 76 int32_t minValue{}; // minimum value 77 int32_t maxValue{}; // maximum value 78 int32_t flat{}; // center flat position, eg. flat == 8 means center is between -8 and 8 79 int32_t fuzz{}; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise 80 int32_t resolution{}; // resolution in units per mm or radians per mm 81 }; 82 83 std::ostream& operator<<(std::ostream& out, const std::optional<RawAbsoluteAxisInfo>& info); 84 85 /* 86 * Input device classes. 87 * 88 * These classes are duplicated in rust side here: /frameworks/native/libs/input/rust/input.rs. 89 * If any new classes are added, we need to add them in rust input side too. 90 */ 91 enum class InputDeviceClass : uint32_t { 92 // LINT.IfChange 93 /* The input device is a keyboard or has buttons. */ 94 KEYBOARD = android::os::IInputConstants::DEVICE_CLASS_KEYBOARD, 95 96 /* The input device is an alpha-numeric keyboard (not just a dial pad). */ 97 ALPHAKEY = android::os::IInputConstants::DEVICE_CLASS_ALPHAKEY, 98 99 /* The input device is a touchscreen or a touchpad (either single-touch or multi-touch). */ 100 TOUCH = android::os::IInputConstants::DEVICE_CLASS_TOUCH, 101 102 /* The input device is a cursor device such as a trackball or mouse. */ 103 CURSOR = android::os::IInputConstants::DEVICE_CLASS_CURSOR, 104 105 /* The input device is a multi-touch touchscreen or touchpad. */ 106 TOUCH_MT = android::os::IInputConstants::DEVICE_CLASS_TOUCH_MT, 107 108 /* The input device is a directional pad (implies keyboard, has DPAD keys). */ 109 DPAD = android::os::IInputConstants::DEVICE_CLASS_DPAD, 110 111 /* The input device is a gamepad (implies keyboard, has BUTTON keys). */ 112 GAMEPAD = android::os::IInputConstants::DEVICE_CLASS_GAMEPAD, 113 114 /* The input device has switches. */ 115 SWITCH = android::os::IInputConstants::DEVICE_CLASS_SWITCH, 116 117 /* The input device is a joystick (implies gamepad, has joystick absolute axes). */ 118 JOYSTICK = android::os::IInputConstants::DEVICE_CLASS_JOYSTICK, 119 120 /* The input device has a vibrator (supports FF_RUMBLE). */ 121 VIBRATOR = android::os::IInputConstants::DEVICE_CLASS_VIBRATOR, 122 123 /* The input device has a microphone. */ 124 MIC = android::os::IInputConstants::DEVICE_CLASS_MIC, 125 126 /* The input device is an external stylus (has data we want to fuse with touch data). */ 127 EXTERNAL_STYLUS = android::os::IInputConstants::DEVICE_CLASS_EXTERNAL_STYLUS, 128 129 /* The input device has a rotary encoder */ 130 ROTARY_ENCODER = android::os::IInputConstants::DEVICE_CLASS_ROTARY_ENCODER, 131 132 /* The input device has a sensor like accelerometer, gyro, etc */ 133 SENSOR = android::os::IInputConstants::DEVICE_CLASS_SENSOR, 134 135 /* The input device has a battery */ 136 BATTERY = android::os::IInputConstants::DEVICE_CLASS_BATTERY, 137 138 /* The input device has sysfs controllable lights */ 139 LIGHT = android::os::IInputConstants::DEVICE_CLASS_LIGHT, 140 141 /* The input device is a touchpad, requiring an on-screen cursor. */ 142 TOUCHPAD = android::os::IInputConstants::DEVICE_CLASS_TOUCHPAD, 143 144 /* The input device is virtual (not a real device, not part of UI configuration). */ 145 VIRTUAL = android::os::IInputConstants::DEVICE_CLASS_VIRTUAL, 146 147 /* The input device is external (not built-in). */ 148 EXTERNAL = android::os::IInputConstants::DEVICE_CLASS_EXTERNAL, 149 // LINT.ThenChange(frameworks/native/services/inputflinger/tests/fuzzers/MapperHelpers.h) 150 }; 151 152 enum class SysfsClass : uint32_t { 153 POWER_SUPPLY = 0, 154 LEDS = 1, 155 156 ftl_last = LEDS 157 }; 158 159 enum class LightColor : uint32_t { 160 RED = 0, 161 GREEN = 1, 162 BLUE = 2, 163 }; 164 165 enum class InputLightClass : uint32_t { 166 /* The input light has brightness node. */ 167 BRIGHTNESS = 0x00000001, 168 /* The input light has red name. */ 169 RED = 0x00000002, 170 /* The input light has green name. */ 171 GREEN = 0x00000004, 172 /* The input light has blue name. */ 173 BLUE = 0x00000008, 174 /* The input light has global name. */ 175 GLOBAL = 0x00000010, 176 /* The input light has multi index node. */ 177 MULTI_INDEX = 0x00000020, 178 /* The input light has multi intensity node. */ 179 MULTI_INTENSITY = 0x00000040, 180 /* The input light has max brightness node. */ 181 MAX_BRIGHTNESS = 0x00000080, 182 /* The input light has kbd_backlight name */ 183 KEYBOARD_BACKLIGHT = 0x00000100, 184 /* The input light has mic_mute name */ 185 KEYBOARD_MIC_MUTE = 0x00000200, 186 /* The input light has mute name */ 187 KEYBOARD_VOLUME_MUTE = 0x00000400, 188 }; 189 190 enum class InputBatteryClass : uint32_t { 191 /* The input device battery has capacity node. */ 192 CAPACITY = 0x00000001, 193 /* The input device battery has capacity_level node. */ 194 CAPACITY_LEVEL = 0x00000002, 195 /* The input device battery has status node. */ 196 STATUS = 0x00000004, 197 }; 198 199 /* Describes a raw light. */ 200 struct RawLightInfo { 201 int32_t id; 202 std::string name; 203 std::optional<int32_t> maxBrightness; 204 ftl::Flags<InputLightClass> flags; 205 std::array<int32_t, COLOR_NUM> rgbIndex; 206 std::filesystem::path path; 207 208 bool operator==(const RawLightInfo&) const = default; 209 bool operator!=(const RawLightInfo&) const = default; 210 }; 211 212 /* Describes a raw battery. */ 213 struct RawBatteryInfo { 214 int32_t id; 215 std::string name; 216 ftl::Flags<InputBatteryClass> flags; 217 std::filesystem::path path; 218 219 bool operator==(const RawBatteryInfo&) const = default; 220 bool operator!=(const RawBatteryInfo&) const = default; 221 }; 222 223 /* Layout information associated with the device */ 224 struct RawLayoutInfo { 225 std::string languageTag; 226 std::string layoutType; 227 228 bool operator==(const RawLayoutInfo&) const = default; 229 bool operator!=(const RawLayoutInfo&) const = default; 230 }; 231 232 /* 233 * Gets the class that owns an axis, in cases where multiple classes might claim 234 * the same axis for different purposes. 235 */ 236 extern ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, 237 ftl::Flags<InputDeviceClass> deviceClasses); 238 239 /* 240 * Grand Central Station for events. 241 * 242 * The event hub aggregates input events received across all known input 243 * devices on the system, including devices that may be emulated by the simulator 244 * environment. In addition, the event hub generates fake input events to indicate 245 * when devices are added or removed. 246 * 247 * The event hub provides a stream of input events (via the getEvent function). 248 * It also supports querying the current actual state of input devices such as identifying 249 * which keys are currently down. Finally, the event hub keeps track of the capabilities of 250 * individual input devices, such as their class and the set of key codes that they support. 251 */ 252 class EventHubInterface { 253 public: EventHubInterface()254 EventHubInterface() {} ~EventHubInterface()255 virtual ~EventHubInterface() {} 256 257 // Synthetic raw event type codes produced when devices are added or removed. 258 enum { 259 // Sent when a device is added. 260 DEVICE_ADDED = 0x10000000, 261 // Sent when a device is removed. 262 DEVICE_REMOVED = 0x20000000, 263 264 FIRST_SYNTHETIC_EVENT = DEVICE_ADDED, 265 }; 266 267 virtual ftl::Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const = 0; 268 269 virtual InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const = 0; 270 271 virtual int32_t getDeviceControllerNumber(int32_t deviceId) const = 0; 272 273 /** 274 * Get the PropertyMap for the provided EventHub device, if available. 275 * This acquires the device lock, so a copy is returned rather than the raw pointer 276 * to the device's PropertyMap. A std::nullopt may be returned if the device could 277 * not be found, or if it doesn't have any configuration. 278 */ 279 virtual std::optional<PropertyMap> getConfiguration(int32_t deviceId) const = 0; 280 281 virtual std::optional<RawAbsoluteAxisInfo> getAbsoluteAxisInfo(int32_t deviceId, 282 int axis) const = 0; 283 284 virtual bool hasRelativeAxis(int32_t deviceId, int axis) const = 0; 285 286 virtual bool hasInputProperty(int32_t deviceId, int property) const = 0; 287 288 virtual bool hasMscEvent(int32_t deviceId, int mscEvent) const = 0; 289 290 virtual void setKeyRemapping(int32_t deviceId, 291 const std::map<int32_t, int32_t>& keyRemapping) const = 0; 292 293 virtual status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, 294 int32_t metaState, int32_t* outKeycode, int32_t* outMetaState, 295 uint32_t* outFlags) const = 0; 296 297 virtual status_t mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const = 0; 298 299 // Sets devices that are excluded from opening. 300 // This can be used to ignore input devices for sensors. 301 virtual void setExcludedDevices(const std::vector<std::string>& devices) = 0; 302 303 /* 304 * Wait for events to become available and returns them. 305 * After returning, the EventHub holds onto a wake lock until the next call to getEvent. 306 * This ensures that the device will not go to sleep while the event is being processed. 307 * If the device needs to remain awake longer than that, then the caller is responsible 308 * for taking care of it (say, by poking the power manager user activity timer). 309 * 310 * The timeout is advisory only. If the device is asleep, it will not wake just to 311 * service the timeout. 312 * 313 * Returns the number of events obtained, or 0 if the timeout expired. 314 */ 315 virtual std::vector<RawEvent> getEvents(int timeoutMillis) = 0; 316 virtual std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) = 0; 317 virtual base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor( 318 int32_t deviceId, int32_t absCode) const = 0; 319 // Raw batteries are sysfs power_supply nodes we found from the EventHub device sysfs node, 320 // containing the raw info of the sysfs node structure. 321 virtual std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const = 0; 322 virtual std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId, 323 int32_t BatteryId) const = 0; 324 325 // Raw lights are sysfs led light nodes we found from the EventHub device sysfs node, 326 // containing the raw info of the sysfs node structure. 327 virtual std::vector<int32_t> getRawLightIds(int32_t deviceId) const = 0; 328 virtual std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, 329 int32_t lightId) const = 0; 330 virtual std::optional<int32_t> getLightBrightness(int32_t deviceId, int32_t lightId) const = 0; 331 virtual void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) = 0; 332 virtual std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities( 333 int32_t deviceId, int32_t lightId) const = 0; 334 virtual void setLightIntensities(int32_t deviceId, int32_t lightId, 335 std::unordered_map<LightColor, int32_t> intensities) = 0; 336 /* Query Layout info associated with the input device. */ 337 virtual std::optional<RawLayoutInfo> getRawLayoutInfo(int32_t deviceId) const = 0; 338 /* Query current input state. */ 339 virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0; 340 virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0; 341 virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0; 342 virtual std::optional<int32_t> getAbsoluteAxisValue(int32_t deviceId, int32_t axis) const = 0; 343 /* Query Multi-Touch slot values for an axis. Returns error or an 1 indexed array of size 344 * (slotCount + 1). The value at the 0 index is set to queried axis. */ 345 virtual base::Result<std::vector<int32_t>> getMtSlotValues(int32_t deviceId, int32_t axis, 346 size_t slotCount) const = 0; 347 virtual int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const = 0; 348 349 /* 350 * Examine key input devices for specific framework keycode support 351 */ 352 virtual bool markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes, 353 uint8_t* outFlags) const = 0; 354 355 virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0; 356 virtual bool hasKeyCode(int32_t deviceId, int32_t keyCode) const = 0; 357 358 /* LED related functions expect Android LED constants, not scan codes or HID usages */ 359 virtual bool hasLed(int32_t deviceId, int32_t led) const = 0; 360 virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0; 361 362 virtual void getVirtualKeyDefinitions( 363 int32_t deviceId, std::vector<VirtualKeyDefinition>& outVirtualKeys) const = 0; 364 365 virtual const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0; 366 virtual bool setKeyboardLayoutOverlay(int32_t deviceId, 367 std::shared_ptr<KeyCharacterMap> map) = 0; 368 369 /* Control the vibrator. */ 370 virtual void vibrate(int32_t deviceId, const VibrationElement& effect) = 0; 371 virtual void cancelVibrate(int32_t deviceId) = 0; 372 virtual std::vector<int32_t> getVibratorIds(int32_t deviceId) const = 0; 373 374 /* Query battery level. */ 375 virtual std::optional<int32_t> getBatteryCapacity(int32_t deviceId, 376 int32_t batteryId) const = 0; 377 378 /* Query battery status. */ 379 virtual std::optional<int32_t> getBatteryStatus(int32_t deviceId, int32_t batteryId) const = 0; 380 381 /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */ 382 virtual void requestReopenDevices() = 0; 383 384 /* Wakes up getEvents() if it is blocked on a read. */ 385 virtual void wake() = 0; 386 387 /* Dump EventHub state to a string. */ 388 virtual void dump(std::string& dump) const = 0; 389 390 /* Called by the heatbeat to ensures that the reader has not deadlocked. */ 391 virtual void monitor() const = 0; 392 393 /* Return true if the device is enabled. */ 394 virtual bool isDeviceEnabled(int32_t deviceId) const = 0; 395 396 /* Enable an input device */ 397 virtual status_t enableDevice(int32_t deviceId) = 0; 398 399 /* Disable an input device. Closes file descriptor to that device. */ 400 virtual status_t disableDevice(int32_t deviceId) = 0; 401 402 /* Gets the sysfs root path for this device. Returns an empty path if there is none. */ 403 virtual std::filesystem::path getSysfsRootPath(int32_t deviceId) const = 0; 404 405 /* Sysfs node changed. Reopen the Eventhub device if any new Peripheral like Light, Battery, 406 * etc. is detected. */ 407 virtual void sysfsNodeChanged(const std::string& sysfsNodePath) = 0; 408 409 /* Set whether the given input device can wake up the kernel from sleep 410 * when it generates input events. By default, usually only internal (built-in) 411 * input devices can wake the kernel from sleep. For an external input device 412 * that supports remote wakeup to be able to wake the kernel, this must be called 413 * after each time the device is connected/added. */ 414 virtual bool setKernelWakeEnabled(int32_t deviceId, bool enabled) = 0; 415 }; 416 417 template <std::size_t BITS> 418 class BitArray { 419 /* Array element type and vector of element type. */ 420 using Element = std::uint32_t; 421 /* Number of bits in each BitArray element. */ 422 static constexpr size_t WIDTH = sizeof(Element) * CHAR_BIT; 423 /* Number of elements to represent a bit array of the specified size of bits. */ 424 static constexpr size_t COUNT = (BITS + WIDTH - 1) / WIDTH; 425 426 public: 427 /* BUFFER type declaration for BitArray */ 428 using Buffer = std::array<Element, COUNT>; 429 /* To tell if a bit is set in array, it selects an element from the array, and test 430 * if the relevant bit set. 431 * Note the parameter "bit" is an index to the bit, 0 <= bit < BITS. 432 */ test(size_t bit)433 inline bool test(size_t bit) const { 434 return (bit < BITS) && mData[bit / WIDTH].test(bit % WIDTH); 435 } 436 /* Sets the given bit in the bit array to given value. 437 * Returns true if the given bit is a valid index and thus was set successfully. 438 */ set(size_t bit,bool value)439 inline bool set(size_t bit, bool value) { 440 if (bit >= BITS) { 441 return false; 442 } 443 mData[bit / WIDTH].set(bit % WIDTH, value); 444 return true; 445 } 446 /* Returns total number of bytes needed for the array */ bytes()447 inline size_t bytes() { return (BITS + CHAR_BIT - 1) / CHAR_BIT; } 448 /* Returns true if array contains any non-zero bit from the range defined by start and end 449 * bit index [startIndex, endIndex). 450 */ any(size_t startIndex,size_t endIndex)451 bool any(size_t startIndex, size_t endIndex) { 452 if (startIndex >= endIndex || startIndex > BITS || endIndex > BITS + 1) { 453 ALOGE("Invalid start/end index. start = %zu, end = %zu, total bits = %zu", startIndex, 454 endIndex, BITS); 455 return false; 456 } 457 size_t se = startIndex / WIDTH; // Start of element 458 size_t ee = endIndex / WIDTH; // End of element 459 size_t si = startIndex % WIDTH; // Start index in start element 460 size_t ei = endIndex % WIDTH; // End index in end element 461 // Need to check first unaligned bitset for any non zero bit 462 if (si > 0) { 463 size_t nBits = se == ee ? ei - si : WIDTH - si; 464 // Generate the mask of interested bit range 465 Element mask = ((1 << nBits) - 1) << si; 466 if (mData[se++].to_ulong() & mask) { 467 return true; 468 } 469 } 470 // Check whole bitset for any bit set 471 for (; se < ee; se++) { 472 if (mData[se].any()) { 473 return true; 474 } 475 } 476 // Need to check last unaligned bitset for any non zero bit 477 if (ei > 0 && se <= ee) { 478 // Generate the mask of interested bit range 479 Element mask = (1 << ei) - 1; 480 if (mData[se].to_ulong() & mask) { 481 return true; 482 } 483 } 484 return false; 485 } 486 /* Load bit array values from buffer */ loadFromBuffer(const Buffer & buffer)487 void loadFromBuffer(const Buffer& buffer) { 488 for (size_t i = 0; i < COUNT; i++) { 489 mData[i] = std::bitset<WIDTH>(buffer[i]); 490 } 491 } 492 /* Dump the indices in the bit array that are set. */ dumpSetIndices(std::string separator,std::function<std::string (size_t)> format)493 inline std::string dumpSetIndices(std::string separator, 494 std::function<std::string(size_t /*index*/)> format) { 495 std::string dmp; 496 for (size_t i = 0; i < BITS; i++) { 497 if (test(i)) { 498 if (!dmp.empty()) { 499 dmp += separator; 500 } 501 dmp += format(i); 502 } 503 } 504 return dmp.empty() ? "<none>" : dmp; 505 } 506 507 private: 508 std::array<std::bitset<WIDTH>, COUNT> mData; 509 }; 510 511 class EventHub : public EventHubInterface { 512 public: 513 EventHub(); 514 515 ftl::Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const override final; 516 517 InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const override final; 518 519 int32_t getDeviceControllerNumber(int32_t deviceId) const override final; 520 521 std::optional<PropertyMap> getConfiguration(int32_t deviceId) const override final; 522 523 std::optional<RawAbsoluteAxisInfo> getAbsoluteAxisInfo(int32_t deviceId, 524 int axis) const override final; 525 526 bool hasRelativeAxis(int32_t deviceId, int axis) const override final; 527 528 bool hasInputProperty(int32_t deviceId, int property) const override final; 529 530 bool hasMscEvent(int32_t deviceId, int mscEvent) const override final; 531 532 void setKeyRemapping(int32_t deviceId, 533 const std::map<int32_t, int32_t>& keyRemapping) const override final; 534 535 status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState, 536 int32_t* outKeycode, int32_t* outMetaState, 537 uint32_t* outFlags) const override final; 538 539 status_t mapAxis(int32_t deviceId, int32_t scanCode, 540 AxisInfo* outAxisInfo) const override final; 541 542 base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor( 543 int32_t deviceId, int32_t absCode) const override final; 544 545 std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const override final; 546 std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId, 547 int32_t BatteryId) const override final; 548 549 std::vector<int32_t> getRawLightIds(int32_t deviceId) const override final; 550 551 std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, 552 int32_t lightId) const override final; 553 554 std::optional<int32_t> getLightBrightness(int32_t deviceId, 555 int32_t lightId) const override final; 556 void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) override final; 557 std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities( 558 int32_t deviceId, int32_t lightId) const override final; 559 void setLightIntensities(int32_t deviceId, int32_t lightId, 560 std::unordered_map<LightColor, int32_t> intensities) override final; 561 562 std::optional<RawLayoutInfo> getRawLayoutInfo(int32_t deviceId) const override final; 563 564 void setExcludedDevices(const std::vector<std::string>& devices) override final; 565 566 int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const override final; 567 int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const override final; 568 int32_t getSwitchState(int32_t deviceId, int32_t sw) const override final; 569 int32_t getKeyCodeForKeyLocation(int32_t deviceId, 570 int32_t locationKeyCode) const override final; 571 std::optional<int32_t> getAbsoluteAxisValue(int32_t deviceId, 572 int32_t axis) const override final; 573 base::Result<std::vector<int32_t>> getMtSlotValues(int32_t deviceId, int32_t axis, 574 size_t slotCount) const override final; 575 576 bool markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes, 577 uint8_t* outFlags) const override final; 578 579 std::vector<RawEvent> getEvents(int timeoutMillis) override final; 580 std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) override final; 581 582 bool hasScanCode(int32_t deviceId, int32_t scanCode) const override final; 583 bool hasKeyCode(int32_t deviceId, int32_t keyCode) const override final; 584 bool hasLed(int32_t deviceId, int32_t led) const override final; 585 void setLedState(int32_t deviceId, int32_t led, bool on) override final; 586 587 void getVirtualKeyDefinitions( 588 int32_t deviceId, 589 std::vector<VirtualKeyDefinition>& outVirtualKeys) const override final; 590 591 const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap( 592 int32_t deviceId) const override final; 593 bool setKeyboardLayoutOverlay(int32_t deviceId, 594 std::shared_ptr<KeyCharacterMap> map) override final; 595 596 void vibrate(int32_t deviceId, const VibrationElement& effect) override final; 597 void cancelVibrate(int32_t deviceId) override final; 598 std::vector<int32_t> getVibratorIds(int32_t deviceId) const override final; 599 600 void requestReopenDevices() override final; 601 602 void wake() override final; 603 604 void dump(std::string& dump) const override final; 605 606 void monitor() const override final; 607 608 std::optional<int32_t> getBatteryCapacity(int32_t deviceId, 609 int32_t batteryId) const override final; 610 611 std::optional<int32_t> getBatteryStatus(int32_t deviceId, 612 int32_t batteryId) const override final; 613 614 bool isDeviceEnabled(int32_t deviceId) const override final; 615 616 status_t enableDevice(int32_t deviceId) override final; 617 618 status_t disableDevice(int32_t deviceId) override final; 619 620 std::filesystem::path getSysfsRootPath(int32_t deviceId) const override final; 621 622 void sysfsNodeChanged(const std::string& sysfsNodePath) override final; 623 624 bool setKernelWakeEnabled(int32_t deviceId, bool enabled) override final; 625 626 ~EventHub() override; 627 628 private: 629 // Holds information about the sysfs device associated with the Device. 630 struct AssociatedDevice { 631 AssociatedDevice(const std::filesystem::path& sysfsRootPath, 632 std::shared_ptr<PropertyMap> baseDevConfig); 633 // The sysfs root path of the misc device. 634 std::filesystem::path sysfsRootPath; 635 // The configuration of the base device. 636 std::shared_ptr<PropertyMap> baseDevConfig; 637 std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> batteryInfos; 638 std::unordered_map<int32_t /*lightId*/, RawLightInfo> lightInfos; 639 std::optional<RawLayoutInfo> layoutInfo; 640 641 bool operator==(const AssociatedDevice&) const = default; 642 bool operator!=(const AssociatedDevice&) const = default; 643 std::string dump() const; 644 }; 645 646 struct Device { 647 int fd; // may be -1 if device is closed 648 const int32_t id; 649 const std::string path; 650 const InputDeviceIdentifier identifier; 651 652 std::unique_ptr<TouchVideoDevice> videoDevice; 653 654 ftl::Flags<InputDeviceClass> classes; 655 656 BitArray<KEY_CNT> keyBitmask; 657 BitArray<KEY_CNT> keyState; 658 BitArray<REL_CNT> relBitmask; 659 BitArray<SW_CNT> swBitmask; 660 BitArray<SW_CNT> swState; 661 BitArray<LED_CNT> ledBitmask; 662 BitArray<FF_CNT> ffBitmask; 663 BitArray<INPUT_PROP_CNT> propBitmask; 664 BitArray<MSC_CNT> mscBitmask; 665 BitArray<ABS_CNT> absBitmask; 666 struct AxisState { 667 RawAbsoluteAxisInfo info; 668 int value; 669 }; 670 std::map<int /*axis*/, AxisState> absState; 671 672 std::string configurationFile; 673 std::shared_ptr<PropertyMap> configuration; 674 std::unique_ptr<VirtualKeyMap> virtualKeyMap; 675 KeyMap keyMap; 676 677 bool ffEffectPlaying; 678 int16_t ffEffectId; // initially -1 679 680 // A shared_ptr of a device associated with the input device. 681 // The input devices that have the same sysfs path have the same associated device. 682 std::shared_ptr<const AssociatedDevice> associatedDevice; 683 684 int32_t controllerNumber; 685 686 Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier, 687 std::shared_ptr<PropertyMap> config); 688 ~Device(); 689 690 void close(); 691 692 bool enabled; // initially true 693 status_t enable(); 694 status_t disable(); 695 bool hasValidFd() const; 696 const bool isVirtual; // set if fd < 0 is passed to constructor 697 698 const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap() const; 699 700 template <std::size_t N> 701 status_t readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray); 702 703 void configureFd(); 704 void populateAbsoluteAxisStates(); 705 bool hasKeycodeLocked(int keycode) const; 706 bool hasKeycodeInternalLocked(int keycode) const; 707 bool loadVirtualKeyMapLocked(); 708 status_t loadKeyMapLocked(); 709 bool isExternalDeviceLocked(); 710 bool deviceHasMicLocked(); 711 void setLedForControllerLocked(); 712 status_t mapLed(int32_t led, int32_t* outScanCode) const; 713 void setLedStateLocked(int32_t led, bool on); 714 715 bool currentFrameDropped; 716 void trackInputEvent(const struct input_event& event); 717 void readDeviceState(); 718 }; 719 720 /** 721 * Create a new device for the provided path. 722 */ 723 void openDeviceLocked(const std::string& devicePath) REQUIRES(mLock); 724 void openVideoDeviceLocked(const std::string& devicePath) REQUIRES(mLock); 725 /** 726 * Try to associate a video device with an input device. If the association succeeds, 727 * the videoDevice is moved into the input device. 'videoDevice' will become null if this 728 * happens. 729 * Return true if the association succeeds. 730 * Return false otherwise. 731 */ 732 bool tryAddVideoDeviceLocked(Device& device, std::unique_ptr<TouchVideoDevice>& videoDevice) 733 REQUIRES(mLock); 734 void createVirtualKeyboardLocked() REQUIRES(mLock); 735 void addDeviceLocked(std::unique_ptr<Device> device) REQUIRES(mLock); 736 void assignDescriptorLocked(InputDeviceIdentifier& identifier) REQUIRES(mLock); 737 std::shared_ptr<const AssociatedDevice> obtainAssociatedDeviceLocked( 738 const std::filesystem::path& devicePath, 739 const std::shared_ptr<PropertyMap>& config) const REQUIRES(mLock); 740 741 void closeDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock); 742 void closeVideoDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock); 743 void closeDeviceLocked(Device& device) REQUIRES(mLock); 744 void closeAllDevicesLocked() REQUIRES(mLock); 745 746 status_t registerFdForEpoll(int fd); 747 status_t unregisterFdFromEpoll(int fd); 748 status_t registerDeviceForEpollLocked(Device& device) REQUIRES(mLock); 749 void registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock); 750 status_t unregisterDeviceFromEpollLocked(Device& device) REQUIRES(mLock); 751 void unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock); 752 753 status_t scanDirLocked(const std::string& dirname) REQUIRES(mLock); 754 status_t scanVideoDirLocked(const std::string& dirname) REQUIRES(mLock); 755 void scanDevicesLocked() REQUIRES(mLock); 756 base::Result<void> readNotifyLocked() REQUIRES(mLock); 757 void handleNotifyEventLocked(const inotify_event&) REQUIRES(mLock); 758 759 Device* getDeviceLocked(int32_t deviceId) const REQUIRES(mLock); 760 Device* getDeviceByPathLocked(const std::string& devicePath) const REQUIRES(mLock); 761 /** 762 * Look through all available fd's (both for input devices and for video devices), 763 * and return the device pointer. 764 */ 765 Device* getDeviceByFdLocked(int fd) const REQUIRES(mLock); 766 767 int32_t getNextControllerNumberLocked(const std::string& name) REQUIRES(mLock); 768 769 bool hasDeviceWithDescriptorLocked(const std::string& descriptor) const REQUIRES(mLock); 770 771 void releaseControllerNumberLocked(int32_t num) REQUIRES(mLock); 772 void reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier, 773 ftl::Flags<InputDeviceClass> classes) REQUIRES(mLock); 774 775 const std::unordered_map<int32_t, RawBatteryInfo>& getBatteryInfoLocked(int32_t deviceId) const 776 REQUIRES(mLock); 777 778 const std::unordered_map<int32_t, RawLightInfo>& getLightInfoLocked(int32_t deviceId) const 779 REQUIRES(mLock); 780 781 void addDeviceInputInotify(); 782 void addDeviceInotify(); 783 784 void handleSysfsNodeChangeNotificationsLocked() REQUIRES(mLock); 785 786 // Protect all internal state. 787 mutable std::mutex mLock; 788 789 // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none. 790 // EventHub remaps the built-in keyboard to id 0 externally as required by the API. 791 enum { 792 // Must not conflict with any other assigned device ids, including 793 // the virtual keyboard id (-1). 794 NO_BUILT_IN_KEYBOARD = -2, 795 }; 796 int32_t mBuiltInKeyboardId; 797 798 int32_t mNextDeviceId; 799 800 BitSet32 mControllerNumbers; 801 802 std::unordered_map<int32_t, std::unique_ptr<Device>> mDevices; 803 /** 804 * Video devices that report touchscreen heatmap, but have not (yet) been paired 805 * with a specific input device. Video device discovery is independent from input device 806 * discovery, so the two types of devices could be found in any order. 807 * Ideally, video devices in this queue do not have an open fd, or at least aren't 808 * actively streaming. 809 */ 810 std::vector<std::unique_ptr<TouchVideoDevice>> mUnattachedVideoDevices; 811 812 std::vector<std::unique_ptr<Device>> mOpeningDevices; 813 std::vector<std::unique_ptr<Device>> mClosingDevices; 814 815 bool mNeedToReopenDevices; 816 bool mNeedToScanDevices; 817 std::vector<std::string> mExcludedDevices; 818 std::vector<int32_t> mDeviceIdsToReopen; 819 820 int mEpollFd; 821 int mINotifyFd; 822 int mWakeReadPipeFd; 823 int mWakeWritePipeFd; 824 825 int mDeviceInputWd; 826 int mDeviceWd = -1; 827 828 // Maximum number of signalled FDs to handle at a time. 829 static const int EPOLL_MAX_EVENTS = 16; 830 831 // The array of pending epoll events and the index of the next event to be handled. 832 struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS]; 833 size_t mPendingEventCount; 834 size_t mPendingEventIndex; 835 bool mPendingINotify; 836 837 // The sysfs node change notifications that have been sent to EventHub. 838 // Enqueuing notifications does not require the lock to be held. 839 BlockingQueue<std::string> mChangedSysfsNodeNotifications; 840 }; 841 842 } // namespace android 843