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