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