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 <ostream> 25 #include <string> 26 #include <unordered_map> 27 #include <utility> 28 #include <vector> 29 30 #include <batteryservice/BatteryService.h> 31 #include <ftl/flags.h> 32 #include <input/Input.h> 33 #include <input/InputDevice.h> 34 #include <input/KeyCharacterMap.h> 35 #include <input/KeyLayoutMap.h> 36 #include <input/Keyboard.h> 37 #include <input/PropertyMap.h> 38 #include <input/VirtualKeyMap.h> 39 #include <linux/input.h> 40 #include <sys/epoll.h> 41 #include <utils/BitSet.h> 42 #include <utils/Errors.h> 43 #include <utils/List.h> 44 #include <utils/Log.h> 45 #include <utils/Mutex.h> 46 47 #include "TouchVideoDevice.h" 48 #include "VibrationElement.h" 49 50 struct inotify_event; 51 52 namespace android { 53 54 /* Number of colors : {red, green, blue} */ 55 static constexpr size_t COLOR_NUM = 3; 56 /* 57 * A raw event as retrieved from the EventHub. 58 */ 59 struct RawEvent { 60 // Time when the event happened 61 nsecs_t when; 62 // Time when the event was read by EventHub. Only populated for input events. 63 // For other events (device added/removed/etc), this value is undefined and should not be read. 64 nsecs_t readTime; 65 int32_t deviceId; 66 int32_t type; 67 int32_t code; 68 int32_t value; 69 }; 70 71 /* Describes an absolute axis. */ 72 struct RawAbsoluteAxisInfo { 73 bool valid{false}; // true if the information is valid, false otherwise 74 75 int32_t minValue{}; // minimum value 76 int32_t maxValue{}; // maximum value 77 int32_t flat{}; // center flat position, eg. flat == 8 means center is between -8 and 8 78 int32_t fuzz{}; // error tolerance, eg. fuzz == 4 means value is +/- 4 due to noise 79 int32_t resolution{}; // resolution in units per mm or radians per mm 80 clearRawAbsoluteAxisInfo81 inline void clear() { *this = RawAbsoluteAxisInfo(); } 82 }; 83 84 std::ostream& operator<<(std::ostream& out, const RawAbsoluteAxisInfo& info); 85 86 /* 87 * Input device classes. 88 * 89 * These classes are duplicated in rust side here: /frameworks/native/libs/input/rust/input.rs. 90 * If any new classes are added, we need to add them in rust input side too. 91 */ 92 enum class InputDeviceClass : uint32_t { 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 }; 150 151 enum class SysfsClass : uint32_t { 152 POWER_SUPPLY = 0, 153 LEDS = 1, 154 155 ftl_last = LEDS 156 }; 157 158 enum class LightColor : uint32_t { 159 RED = 0, 160 GREEN = 1, 161 BLUE = 2, 162 }; 163 164 enum class InputLightClass : uint32_t { 165 /* The input light has brightness node. */ 166 BRIGHTNESS = 0x00000001, 167 /* The input light has red name. */ 168 RED = 0x00000002, 169 /* The input light has green name. */ 170 GREEN = 0x00000004, 171 /* The input light has blue name. */ 172 BLUE = 0x00000008, 173 /* The input light has global name. */ 174 GLOBAL = 0x00000010, 175 /* The input light has multi index node. */ 176 MULTI_INDEX = 0x00000020, 177 /* The input light has multi intensity node. */ 178 MULTI_INTENSITY = 0x00000040, 179 /* The input light has max brightness node. */ 180 MAX_BRIGHTNESS = 0x00000080, 181 /* The input light has kbd_backlight name */ 182 KEYBOARD_BACKLIGHT = 0x00000100, 183 /* The input light has mic_mute name */ 184 KEYBOARD_MIC_MUTE = 0x00000200, 185 }; 186 187 enum class InputBatteryClass : uint32_t { 188 /* The input device battery has capacity node. */ 189 CAPACITY = 0x00000001, 190 /* The input device battery has capacity_level node. */ 191 CAPACITY_LEVEL = 0x00000002, 192 /* The input device battery has status node. */ 193 STATUS = 0x00000004, 194 }; 195 196 /* Describes a raw light. */ 197 struct RawLightInfo { 198 int32_t id; 199 std::string name; 200 std::optional<int32_t> maxBrightness; 201 ftl::Flags<InputLightClass> flags; 202 std::array<int32_t, COLOR_NUM> rgbIndex; 203 std::filesystem::path path; 204 205 bool operator==(const RawLightInfo&) const = default; 206 bool operator!=(const RawLightInfo&) const = default; 207 }; 208 209 /* Describes a raw battery. */ 210 struct RawBatteryInfo { 211 int32_t id; 212 std::string name; 213 ftl::Flags<InputBatteryClass> flags; 214 std::filesystem::path path; 215 216 bool operator==(const RawBatteryInfo&) const = default; 217 bool operator!=(const RawBatteryInfo&) const = default; 218 }; 219 220 /* Layout information associated with the device */ 221 struct RawLayoutInfo { 222 std::string languageTag; 223 std::string layoutType; 224 225 bool operator==(const RawLayoutInfo&) const = default; 226 bool operator!=(const RawLayoutInfo&) const = default; 227 }; 228 229 /* 230 * Gets the class that owns an axis, in cases where multiple classes might claim 231 * the same axis for different purposes. 232 */ 233 extern ftl::Flags<InputDeviceClass> getAbsAxisUsage(int32_t axis, 234 ftl::Flags<InputDeviceClass> deviceClasses); 235 236 /* 237 * Grand Central Station for events. 238 * 239 * The event hub aggregates input events received across all known input 240 * devices on the system, including devices that may be emulated by the simulator 241 * environment. In addition, the event hub generates fake input events to indicate 242 * when devices are added or removed. 243 * 244 * The event hub provides a stream of input events (via the getEvent function). 245 * It also supports querying the current actual state of input devices such as identifying 246 * which keys are currently down. Finally, the event hub keeps track of the capabilities of 247 * individual input devices, such as their class and the set of key codes that they support. 248 */ 249 class EventHubInterface { 250 public: EventHubInterface()251 EventHubInterface() {} ~EventHubInterface()252 virtual ~EventHubInterface() {} 253 254 // Synthetic raw event type codes produced when devices are added or removed. 255 enum { 256 // Sent when a device is added. 257 DEVICE_ADDED = 0x10000000, 258 // Sent when a device is removed. 259 DEVICE_REMOVED = 0x20000000, 260 // Sent when all added/removed devices from the most recent scan have been reported. 261 // This event is always sent at least once. 262 FINISHED_DEVICE_SCAN = 0x30000000, 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 status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, 282 RawAbsoluteAxisInfo* outAxisInfo) 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 addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, 291 int32_t toKeyCode) 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 status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, 343 int32_t* outValue) const = 0; 344 /* Query Multi-Touch slot values for an axis. Returns error or an 1 indexed array of size 345 * (slotCount + 1). The value at the 0 index is set to queried axis. */ 346 virtual base::Result<std::vector<int32_t>> getMtSlotValues(int32_t deviceId, int32_t axis, 347 size_t slotCount) const = 0; 348 virtual int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const = 0; 349 350 /* 351 * Examine key input devices for specific framework keycode support 352 */ 353 virtual bool markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes, 354 uint8_t* outFlags) const = 0; 355 356 virtual bool hasScanCode(int32_t deviceId, int32_t scanCode) const = 0; 357 virtual bool hasKeyCode(int32_t deviceId, int32_t keyCode) const = 0; 358 359 /* LED related functions expect Android LED constants, not scan codes or HID usages */ 360 virtual bool hasLed(int32_t deviceId, int32_t led) const = 0; 361 virtual void setLedState(int32_t deviceId, int32_t led, bool on) = 0; 362 363 virtual void getVirtualKeyDefinitions( 364 int32_t deviceId, std::vector<VirtualKeyDefinition>& outVirtualKeys) const = 0; 365 366 virtual const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const = 0; 367 virtual bool setKeyboardLayoutOverlay(int32_t deviceId, 368 std::shared_ptr<KeyCharacterMap> map) = 0; 369 370 /* Control the vibrator. */ 371 virtual void vibrate(int32_t deviceId, const VibrationElement& effect) = 0; 372 virtual void cancelVibrate(int32_t deviceId) = 0; 373 virtual std::vector<int32_t> getVibratorIds(int32_t deviceId) const = 0; 374 375 /* Query battery level. */ 376 virtual std::optional<int32_t> getBatteryCapacity(int32_t deviceId, 377 int32_t batteryId) const = 0; 378 379 /* Query battery status. */ 380 virtual std::optional<int32_t> getBatteryStatus(int32_t deviceId, int32_t batteryId) const = 0; 381 382 /* Requests the EventHub to reopen all input devices on the next call to getEvents(). */ 383 virtual void requestReopenDevices() = 0; 384 385 /* Wakes up getEvents() if it is blocked on a read. */ 386 virtual void wake() = 0; 387 388 /* Dump EventHub state to a string. */ 389 virtual void dump(std::string& dump) const = 0; 390 391 /* Called by the heatbeat to ensures that the reader has not deadlocked. */ 392 virtual void monitor() const = 0; 393 394 /* Return true if the device is enabled. */ 395 virtual bool isDeviceEnabled(int32_t deviceId) const = 0; 396 397 /* Enable an input device */ 398 virtual status_t enableDevice(int32_t deviceId) = 0; 399 400 /* Disable an input device. Closes file descriptor to that device. */ 401 virtual status_t disableDevice(int32_t deviceId) = 0; 402 403 /* Sysfs node changed. Reopen the Eventhub device if any new Peripheral like Light, Battery, 404 * etc. is detected. */ 405 virtual void sysfsNodeChanged(const std::string& sysfsNodePath) = 0; 406 }; 407 408 template <std::size_t BITS> 409 class BitArray { 410 /* Array element type and vector of element type. */ 411 using Element = std::uint32_t; 412 /* Number of bits in each BitArray element. */ 413 static constexpr size_t WIDTH = sizeof(Element) * CHAR_BIT; 414 /* Number of elements to represent a bit array of the specified size of bits. */ 415 static constexpr size_t COUNT = (BITS + WIDTH - 1) / WIDTH; 416 417 public: 418 /* BUFFER type declaration for BitArray */ 419 using Buffer = std::array<Element, COUNT>; 420 /* To tell if a bit is set in array, it selects an element from the array, and test 421 * if the relevant bit set. 422 * Note the parameter "bit" is an index to the bit, 0 <= bit < BITS. 423 */ test(size_t bit)424 inline bool test(size_t bit) const { 425 return (bit < BITS) && mData[bit / WIDTH].test(bit % WIDTH); 426 } 427 /* Sets the given bit in the bit array to given value. 428 * Returns true if the given bit is a valid index and thus was set successfully. 429 */ set(size_t bit,bool value)430 inline bool set(size_t bit, bool value) { 431 if (bit >= BITS) { 432 return false; 433 } 434 mData[bit / WIDTH].set(bit % WIDTH, value); 435 return true; 436 } 437 /* Returns total number of bytes needed for the array */ bytes()438 inline size_t bytes() { return (BITS + CHAR_BIT - 1) / CHAR_BIT; } 439 /* Returns true if array contains any non-zero bit from the range defined by start and end 440 * bit index [startIndex, endIndex). 441 */ any(size_t startIndex,size_t endIndex)442 bool any(size_t startIndex, size_t endIndex) { 443 if (startIndex >= endIndex || startIndex > BITS || endIndex > BITS + 1) { 444 ALOGE("Invalid start/end index. start = %zu, end = %zu, total bits = %zu", startIndex, 445 endIndex, BITS); 446 return false; 447 } 448 size_t se = startIndex / WIDTH; // Start of element 449 size_t ee = endIndex / WIDTH; // End of element 450 size_t si = startIndex % WIDTH; // Start index in start element 451 size_t ei = endIndex % WIDTH; // End index in end element 452 // Need to check first unaligned bitset for any non zero bit 453 if (si > 0) { 454 size_t nBits = se == ee ? ei - si : WIDTH - si; 455 // Generate the mask of interested bit range 456 Element mask = ((1 << nBits) - 1) << si; 457 if (mData[se++].to_ulong() & mask) { 458 return true; 459 } 460 } 461 // Check whole bitset for any bit set 462 for (; se < ee; se++) { 463 if (mData[se].any()) { 464 return true; 465 } 466 } 467 // Need to check last unaligned bitset for any non zero bit 468 if (ei > 0 && se <= ee) { 469 // Generate the mask of interested bit range 470 Element mask = (1 << ei) - 1; 471 if (mData[se].to_ulong() & mask) { 472 return true; 473 } 474 } 475 return false; 476 } 477 /* Load bit array values from buffer */ loadFromBuffer(const Buffer & buffer)478 void loadFromBuffer(const Buffer& buffer) { 479 for (size_t i = 0; i < COUNT; i++) { 480 mData[i] = std::bitset<WIDTH>(buffer[i]); 481 } 482 } 483 /* Dump the indices in the bit array that are set. */ dumpSetIndices(std::string separator,std::function<std::string (size_t)> format)484 inline std::string dumpSetIndices(std::string separator, 485 std::function<std::string(size_t /*index*/)> format) { 486 std::string dmp; 487 for (size_t i = 0; i < BITS; i++) { 488 if (test(i)) { 489 if (!dmp.empty()) { 490 dmp += separator; 491 } 492 dmp += format(i); 493 } 494 } 495 return dmp.empty() ? "<none>" : dmp; 496 } 497 498 private: 499 std::array<std::bitset<WIDTH>, COUNT> mData; 500 }; 501 502 class EventHub : public EventHubInterface { 503 public: 504 EventHub(); 505 506 ftl::Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const override final; 507 508 InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const override final; 509 510 int32_t getDeviceControllerNumber(int32_t deviceId) const override final; 511 512 std::optional<PropertyMap> getConfiguration(int32_t deviceId) const override final; 513 514 status_t getAbsoluteAxisInfo(int32_t deviceId, int axis, 515 RawAbsoluteAxisInfo* outAxisInfo) const override final; 516 517 bool hasRelativeAxis(int32_t deviceId, int axis) const override final; 518 519 bool hasInputProperty(int32_t deviceId, int property) const override final; 520 521 bool hasMscEvent(int32_t deviceId, int mscEvent) const override final; 522 523 void addKeyRemapping(int32_t deviceId, int32_t fromKeyCode, 524 int32_t toKeyCode) const override final; 525 526 status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState, 527 int32_t* outKeycode, int32_t* outMetaState, 528 uint32_t* outFlags) const override final; 529 530 status_t mapAxis(int32_t deviceId, int32_t scanCode, 531 AxisInfo* outAxisInfo) const override final; 532 533 base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor( 534 int32_t deviceId, int32_t absCode) const override final; 535 536 std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const override final; 537 std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId, 538 int32_t BatteryId) const override final; 539 540 std::vector<int32_t> getRawLightIds(int32_t deviceId) const override final; 541 542 std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, 543 int32_t lightId) const override final; 544 545 std::optional<int32_t> getLightBrightness(int32_t deviceId, 546 int32_t lightId) const override final; 547 void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) override final; 548 std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities( 549 int32_t deviceId, int32_t lightId) const override final; 550 void setLightIntensities(int32_t deviceId, int32_t lightId, 551 std::unordered_map<LightColor, int32_t> intensities) override final; 552 553 std::optional<RawLayoutInfo> getRawLayoutInfo(int32_t deviceId) const override final; 554 555 void setExcludedDevices(const std::vector<std::string>& devices) override final; 556 557 int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const override final; 558 int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const override final; 559 int32_t getSwitchState(int32_t deviceId, int32_t sw) const override final; 560 int32_t getKeyCodeForKeyLocation(int32_t deviceId, 561 int32_t locationKeyCode) const override final; 562 status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis, 563 int32_t* outValue) const override final; 564 base::Result<std::vector<int32_t>> getMtSlotValues(int32_t deviceId, int32_t axis, 565 size_t slotCount) const override final; 566 567 bool markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes, 568 uint8_t* outFlags) const override final; 569 570 std::vector<RawEvent> getEvents(int timeoutMillis) override final; 571 std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) override final; 572 573 bool hasScanCode(int32_t deviceId, int32_t scanCode) const override final; 574 bool hasKeyCode(int32_t deviceId, int32_t keyCode) const override final; 575 bool hasLed(int32_t deviceId, int32_t led) const override final; 576 void setLedState(int32_t deviceId, int32_t led, bool on) override final; 577 578 void getVirtualKeyDefinitions( 579 int32_t deviceId, 580 std::vector<VirtualKeyDefinition>& outVirtualKeys) const override final; 581 582 const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap( 583 int32_t deviceId) const override final; 584 bool setKeyboardLayoutOverlay(int32_t deviceId, 585 std::shared_ptr<KeyCharacterMap> map) override final; 586 587 void vibrate(int32_t deviceId, const VibrationElement& effect) override final; 588 void cancelVibrate(int32_t deviceId) override final; 589 std::vector<int32_t> getVibratorIds(int32_t deviceId) const override final; 590 591 void requestReopenDevices() override final; 592 593 void wake() override final; 594 595 void dump(std::string& dump) const override final; 596 597 void monitor() const override final; 598 599 std::optional<int32_t> getBatteryCapacity(int32_t deviceId, 600 int32_t batteryId) const override final; 601 602 std::optional<int32_t> getBatteryStatus(int32_t deviceId, 603 int32_t batteryId) const override final; 604 605 bool isDeviceEnabled(int32_t deviceId) const override final; 606 607 status_t enableDevice(int32_t deviceId) override final; 608 609 status_t disableDevice(int32_t deviceId) override final; 610 611 void sysfsNodeChanged(const std::string& sysfsNodePath) override final; 612 613 ~EventHub() override; 614 615 private: 616 // Holds information about the sysfs device associated with the Device. 617 struct AssociatedDevice { 618 // The sysfs root path of the misc device. 619 std::filesystem::path sysfsRootPath; 620 std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> batteryInfos; 621 std::unordered_map<int32_t /*lightId*/, RawLightInfo> lightInfos; 622 std::optional<RawLayoutInfo> layoutInfo; 623 624 bool isChanged() const; 625 bool operator==(const AssociatedDevice&) const = default; 626 bool operator!=(const AssociatedDevice&) const = default; 627 std::string dump() const; 628 }; 629 630 struct Device { 631 int fd; // may be -1 if device is closed 632 const int32_t id; 633 const std::string path; 634 const InputDeviceIdentifier identifier; 635 636 std::unique_ptr<TouchVideoDevice> videoDevice; 637 638 ftl::Flags<InputDeviceClass> classes; 639 640 BitArray<KEY_CNT> keyBitmask; 641 BitArray<KEY_CNT> keyState; 642 BitArray<REL_CNT> relBitmask; 643 BitArray<SW_CNT> swBitmask; 644 BitArray<SW_CNT> swState; 645 BitArray<LED_CNT> ledBitmask; 646 BitArray<FF_CNT> ffBitmask; 647 BitArray<INPUT_PROP_CNT> propBitmask; 648 BitArray<MSC_CNT> mscBitmask; 649 BitArray<ABS_CNT> absBitmask; 650 struct AxisState { 651 RawAbsoluteAxisInfo info; 652 int value; 653 }; 654 std::map<int /*axis*/, AxisState> absState; 655 656 std::string configurationFile; 657 std::unique_ptr<PropertyMap> configuration; 658 std::unique_ptr<VirtualKeyMap> virtualKeyMap; 659 KeyMap keyMap; 660 661 bool ffEffectPlaying; 662 int16_t ffEffectId; // initially -1 663 664 // A shared_ptr of a device associated with the input device. 665 // The input devices that have the same sysfs path have the same associated device. 666 std::shared_ptr<const AssociatedDevice> associatedDevice; 667 668 int32_t controllerNumber; 669 670 Device(int fd, int32_t id, std::string path, InputDeviceIdentifier identifier, 671 std::shared_ptr<const AssociatedDevice> assocDev); 672 ~Device(); 673 674 void close(); 675 676 bool enabled; // initially true 677 status_t enable(); 678 status_t disable(); 679 bool hasValidFd() const; 680 const bool isVirtual; // set if fd < 0 is passed to constructor 681 682 const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap() const; 683 684 template <std::size_t N> 685 status_t readDeviceBitMask(unsigned long ioctlCode, BitArray<N>& bitArray); 686 687 void configureFd(); 688 void populateAbsoluteAxisStates(); 689 bool hasKeycodeLocked(int keycode) const; 690 void loadConfigurationLocked(); 691 bool loadVirtualKeyMapLocked(); 692 status_t loadKeyMapLocked(); 693 bool isExternalDeviceLocked(); 694 bool deviceHasMicLocked(); 695 void setLedForControllerLocked(); 696 status_t mapLed(int32_t led, int32_t* outScanCode) const; 697 void setLedStateLocked(int32_t led, bool on); 698 699 bool currentFrameDropped; 700 void trackInputEvent(const struct input_event& event); 701 void readDeviceState(); 702 }; 703 704 /** 705 * Create a new device for the provided path. 706 */ 707 void openDeviceLocked(const std::string& devicePath) REQUIRES(mLock); 708 void openVideoDeviceLocked(const std::string& devicePath) REQUIRES(mLock); 709 /** 710 * Try to associate a video device with an input device. If the association succeeds, 711 * the videoDevice is moved into the input device. 'videoDevice' will become null if this 712 * happens. 713 * Return true if the association succeeds. 714 * Return false otherwise. 715 */ 716 bool tryAddVideoDeviceLocked(Device& device, std::unique_ptr<TouchVideoDevice>& videoDevice) 717 REQUIRES(mLock); 718 void createVirtualKeyboardLocked() REQUIRES(mLock); 719 void addDeviceLocked(std::unique_ptr<Device> device) REQUIRES(mLock); 720 void assignDescriptorLocked(InputDeviceIdentifier& identifier) REQUIRES(mLock); 721 std::shared_ptr<const AssociatedDevice> obtainAssociatedDeviceLocked( 722 const std::filesystem::path& devicePath) const REQUIRES(mLock); 723 724 void closeDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock); 725 void closeVideoDeviceByPathLocked(const std::string& devicePath) REQUIRES(mLock); 726 void closeDeviceLocked(Device& device) REQUIRES(mLock); 727 void closeAllDevicesLocked() REQUIRES(mLock); 728 729 status_t registerFdForEpoll(int fd); 730 status_t unregisterFdFromEpoll(int fd); 731 status_t registerDeviceForEpollLocked(Device& device) REQUIRES(mLock); 732 void registerVideoDeviceForEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock); 733 status_t unregisterDeviceFromEpollLocked(Device& device) REQUIRES(mLock); 734 void unregisterVideoDeviceFromEpollLocked(const TouchVideoDevice& videoDevice) REQUIRES(mLock); 735 736 status_t scanDirLocked(const std::string& dirname) REQUIRES(mLock); 737 status_t scanVideoDirLocked(const std::string& dirname) REQUIRES(mLock); 738 void scanDevicesLocked() REQUIRES(mLock); 739 base::Result<void> readNotifyLocked() REQUIRES(mLock); 740 void handleNotifyEventLocked(const inotify_event&) REQUIRES(mLock); 741 742 Device* getDeviceLocked(int32_t deviceId) const REQUIRES(mLock); 743 Device* getDeviceByPathLocked(const std::string& devicePath) const REQUIRES(mLock); 744 /** 745 * Look through all available fd's (both for input devices and for video devices), 746 * and return the device pointer. 747 */ 748 Device* getDeviceByFdLocked(int fd) const REQUIRES(mLock); 749 750 int32_t getNextControllerNumberLocked(const std::string& name) REQUIRES(mLock); 751 752 bool hasDeviceWithDescriptorLocked(const std::string& descriptor) const REQUIRES(mLock); 753 754 void releaseControllerNumberLocked(int32_t num) REQUIRES(mLock); 755 void reportDeviceAddedForStatisticsLocked(const InputDeviceIdentifier& identifier, 756 ftl::Flags<InputDeviceClass> classes) REQUIRES(mLock); 757 758 const std::unordered_map<int32_t, RawBatteryInfo>& getBatteryInfoLocked(int32_t deviceId) const 759 REQUIRES(mLock); 760 761 const std::unordered_map<int32_t, RawLightInfo>& getLightInfoLocked(int32_t deviceId) const 762 REQUIRES(mLock); 763 764 void addDeviceInputInotify(); 765 void addDeviceInotify(); 766 767 // Protect all internal state. 768 mutable std::mutex mLock; 769 770 // The actual id of the built-in keyboard, or NO_BUILT_IN_KEYBOARD if none. 771 // EventHub remaps the built-in keyboard to id 0 externally as required by the API. 772 enum { 773 // Must not conflict with any other assigned device ids, including 774 // the virtual keyboard id (-1). 775 NO_BUILT_IN_KEYBOARD = -2, 776 }; 777 int32_t mBuiltInKeyboardId; 778 779 int32_t mNextDeviceId; 780 781 BitSet32 mControllerNumbers; 782 783 std::unordered_map<int32_t, std::unique_ptr<Device>> mDevices; 784 /** 785 * Video devices that report touchscreen heatmap, but have not (yet) been paired 786 * with a specific input device. Video device discovery is independent from input device 787 * discovery, so the two types of devices could be found in any order. 788 * Ideally, video devices in this queue do not have an open fd, or at least aren't 789 * actively streaming. 790 */ 791 std::vector<std::unique_ptr<TouchVideoDevice>> mUnattachedVideoDevices; 792 793 std::vector<std::unique_ptr<Device>> mOpeningDevices; 794 std::vector<std::unique_ptr<Device>> mClosingDevices; 795 796 bool mNeedToSendFinishedDeviceScan; 797 bool mNeedToReopenDevices; 798 bool mNeedToScanDevices; 799 std::vector<std::string> mExcludedDevices; 800 801 int mEpollFd; 802 int mINotifyFd; 803 int mWakeReadPipeFd; 804 int mWakeWritePipeFd; 805 806 int mDeviceInputWd; 807 int mDeviceWd = -1; 808 809 // Maximum number of signalled FDs to handle at a time. 810 static const int EPOLL_MAX_EVENTS = 16; 811 812 // The array of pending epoll events and the index of the next event to be handled. 813 struct epoll_event mPendingEventItems[EPOLL_MAX_EVENTS]; 814 size_t mPendingEventCount; 815 size_t mPendingEventIndex; 816 bool mPendingINotify; 817 }; 818 819 } // namespace android 820