1 /* 2 * Copyright (C) 2010 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 #ifndef _UI_INPUT_READER_H 18 #define _UI_INPUT_READER_H 19 20 #include "EventHub.h" 21 #include "PointerControllerInterface.h" 22 #include "InputListener.h" 23 24 #include <input/Input.h> 25 #include <input/VelocityControl.h> 26 #include <input/VelocityTracker.h> 27 #include <ui/DisplayInfo.h> 28 #include <utils/KeyedVector.h> 29 #include <utils/threads.h> 30 #include <utils/Timers.h> 31 #include <utils/RefBase.h> 32 #include <utils/String8.h> 33 #include <utils/BitSet.h> 34 35 #include <stddef.h> 36 #include <unistd.h> 37 38 // Maximum supported size of a vibration pattern. 39 // Must be at least 2. 40 #define MAX_VIBRATE_PATTERN_SIZE 100 41 42 // Maximum allowable delay value in a vibration pattern before 43 // which the delay will be truncated. 44 #define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL) 45 46 namespace android { 47 48 class InputDevice; 49 class InputMapper; 50 51 /* 52 * Describes how coordinates are mapped on a physical display. 53 * See com.android.server.display.DisplayViewport. 54 */ 55 struct DisplayViewport { 56 int32_t displayId; // -1 if invalid 57 int32_t orientation; 58 int32_t logicalLeft; 59 int32_t logicalTop; 60 int32_t logicalRight; 61 int32_t logicalBottom; 62 int32_t physicalLeft; 63 int32_t physicalTop; 64 int32_t physicalRight; 65 int32_t physicalBottom; 66 int32_t deviceWidth; 67 int32_t deviceHeight; 68 69 DisplayViewport() : 70 displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0), 71 logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0), 72 physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0), 73 deviceWidth(0), deviceHeight(0) { 74 } 75 76 bool operator==(const DisplayViewport& other) const { 77 return displayId == other.displayId 78 && orientation == other.orientation 79 && logicalLeft == other.logicalLeft 80 && logicalTop == other.logicalTop 81 && logicalRight == other.logicalRight 82 && logicalBottom == other.logicalBottom 83 && physicalLeft == other.physicalLeft 84 && physicalTop == other.physicalTop 85 && physicalRight == other.physicalRight 86 && physicalBottom == other.physicalBottom 87 && deviceWidth == other.deviceWidth 88 && deviceHeight == other.deviceHeight; 89 } 90 91 bool operator!=(const DisplayViewport& other) const { 92 return !(*this == other); 93 } 94 95 inline bool isValid() const { 96 return displayId >= 0; 97 } 98 99 void setNonDisplayViewport(int32_t width, int32_t height) { 100 displayId = ADISPLAY_ID_NONE; 101 orientation = DISPLAY_ORIENTATION_0; 102 logicalLeft = 0; 103 logicalTop = 0; 104 logicalRight = width; 105 logicalBottom = height; 106 physicalLeft = 0; 107 physicalTop = 0; 108 physicalRight = width; 109 physicalBottom = height; 110 deviceWidth = width; 111 deviceHeight = height; 112 } 113 }; 114 115 /* 116 * Input reader configuration. 117 * 118 * Specifies various options that modify the behavior of the input reader. 119 */ 120 struct InputReaderConfiguration { 121 // Describes changes that have occurred. 122 enum { 123 // The pointer speed changed. 124 CHANGE_POINTER_SPEED = 1 << 0, 125 126 // The pointer gesture control changed. 127 CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1, 128 129 // The display size or orientation changed. 130 CHANGE_DISPLAY_INFO = 1 << 2, 131 132 // The visible touches option changed. 133 CHANGE_SHOW_TOUCHES = 1 << 3, 134 135 // The keyboard layouts must be reloaded. 136 CHANGE_KEYBOARD_LAYOUTS = 1 << 4, 137 138 // The device name alias supplied by the may have changed for some devices. 139 CHANGE_DEVICE_ALIAS = 1 << 5, 140 141 // The location calibration matrix changed. 142 TOUCH_AFFINE_TRANSFORMATION = 1 << 6, 143 144 // All devices must be reopened. 145 CHANGE_MUST_REOPEN = 1 << 31, 146 }; 147 148 // Gets the amount of time to disable virtual keys after the screen is touched 149 // in order to filter out accidental virtual key presses due to swiping gestures 150 // or taps near the edge of the display. May be 0 to disable the feature. 151 nsecs_t virtualKeyQuietTime; 152 153 // The excluded device names for the platform. 154 // Devices with these names will be ignored. 155 Vector<String8> excludedDeviceNames; 156 157 // Velocity control parameters for mouse pointer movements. 158 VelocityControlParameters pointerVelocityControlParameters; 159 160 // Velocity control parameters for mouse wheel movements. 161 VelocityControlParameters wheelVelocityControlParameters; 162 163 // True if pointer gestures are enabled. 164 bool pointerGesturesEnabled; 165 166 // Quiet time between certain pointer gesture transitions. 167 // Time to allow for all fingers or buttons to settle into a stable state before 168 // starting a new gesture. 169 nsecs_t pointerGestureQuietInterval; 170 171 // The minimum speed that a pointer must travel for us to consider switching the active 172 // touch pointer to it during a drag. This threshold is set to avoid switching due 173 // to noise from a finger resting on the touch pad (perhaps just pressing it down). 174 float pointerGestureDragMinSwitchSpeed; // in pixels per second 175 176 // Tap gesture delay time. 177 // The time between down and up must be less than this to be considered a tap. 178 nsecs_t pointerGestureTapInterval; 179 180 // Tap drag gesture delay time. 181 // The time between the previous tap's up and the next down must be less than 182 // this to be considered a drag. Otherwise, the previous tap is finished and a 183 // new tap begins. 184 // 185 // Note that the previous tap will be held down for this entire duration so this 186 // interval must be shorter than the long press timeout. 187 nsecs_t pointerGestureTapDragInterval; 188 189 // The distance in pixels that the pointer is allowed to move from initial down 190 // to up and still be called a tap. 191 float pointerGestureTapSlop; // in pixels 192 193 // Time after the first touch points go down to settle on an initial centroid. 194 // This is intended to be enough time to handle cases where the user puts down two 195 // fingers at almost but not quite exactly the same time. 196 nsecs_t pointerGestureMultitouchSettleInterval; 197 198 // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when 199 // at least two pointers have moved at least this far from their starting place. 200 float pointerGestureMultitouchMinDistance; // in pixels 201 202 // The transition from PRESS to SWIPE gesture mode can only occur when the 203 // cosine of the angle between the two vectors is greater than or equal to than this value 204 // which indicates that the vectors are oriented in the same direction. 205 // When the vectors are oriented in the exactly same direction, the cosine is 1.0. 206 // (In exactly opposite directions, the cosine is -1.0.) 207 float pointerGestureSwipeTransitionAngleCosine; 208 209 // The transition from PRESS to SWIPE gesture mode can only occur when the 210 // fingers are no more than this far apart relative to the diagonal size of 211 // the touch pad. For example, a ratio of 0.5 means that the fingers must be 212 // no more than half the diagonal size of the touch pad apart. 213 float pointerGestureSwipeMaxWidthRatio; 214 215 // The gesture movement speed factor relative to the size of the display. 216 // Movement speed applies when the fingers are moving in the same direction. 217 // Without acceleration, a full swipe of the touch pad diagonal in movement mode 218 // will cover this portion of the display diagonal. 219 float pointerGestureMovementSpeedRatio; 220 221 // The gesture zoom speed factor relative to the size of the display. 222 // Zoom speed applies when the fingers are mostly moving relative to each other 223 // to execute a scale gesture or similar. 224 // Without acceleration, a full swipe of the touch pad diagonal in zoom mode 225 // will cover this portion of the display diagonal. 226 float pointerGestureZoomSpeedRatio; 227 228 // True to show the location of touches on the touch screen as spots. 229 bool showTouches; 230 231 InputReaderConfiguration() : 232 virtualKeyQuietTime(0), 233 pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f), 234 wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f), 235 pointerGesturesEnabled(true), 236 pointerGestureQuietInterval(100 * 1000000LL), // 100 ms 237 pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second 238 pointerGestureTapInterval(150 * 1000000LL), // 150 ms 239 pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms 240 pointerGestureTapSlop(10.0f), // 10 pixels 241 pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms 242 pointerGestureMultitouchMinDistance(15), // 15 pixels 243 pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees 244 pointerGestureSwipeMaxWidthRatio(0.25f), 245 pointerGestureMovementSpeedRatio(0.8f), 246 pointerGestureZoomSpeedRatio(0.3f), 247 showTouches(false) { } 248 249 bool getDisplayInfo(bool external, DisplayViewport* outViewport) const; 250 void setDisplayInfo(bool external, const DisplayViewport& viewport); 251 252 private: 253 DisplayViewport mInternalDisplay; 254 DisplayViewport mExternalDisplay; 255 }; 256 257 258 struct TouchAffineTransformation { 259 float x_scale; 260 float x_ymix; 261 float x_offset; 262 float y_xmix; 263 float y_scale; 264 float y_offset; 265 266 TouchAffineTransformation() : 267 x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f), 268 y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) { 269 } 270 271 TouchAffineTransformation(float xscale, float xymix, float xoffset, 272 float yxmix, float yscale, float yoffset) : 273 x_scale(xscale), x_ymix(xymix), x_offset(xoffset), 274 y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) { 275 } 276 277 void applyTo(float& x, float& y) const; 278 }; 279 280 281 /* 282 * Input reader policy interface. 283 * 284 * The input reader policy is used by the input reader to interact with the Window Manager 285 * and other system components. 286 * 287 * The actual implementation is partially supported by callbacks into the DVM 288 * via JNI. This interface is also mocked in the unit tests. 289 * 290 * These methods must NOT re-enter the input reader since they may be called while 291 * holding the input reader lock. 292 */ 293 class InputReaderPolicyInterface : public virtual RefBase { 294 protected: 295 InputReaderPolicyInterface() { } 296 virtual ~InputReaderPolicyInterface() { } 297 298 public: 299 /* Gets the input reader configuration. */ 300 virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0; 301 302 /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */ 303 virtual sp<PointerControllerInterface> obtainPointerController(int32_t deviceId) = 0; 304 305 /* Notifies the input reader policy that some input devices have changed 306 * and provides information about all current input devices. 307 */ 308 virtual void notifyInputDevicesChanged(const Vector<InputDeviceInfo>& inputDevices) = 0; 309 310 /* Gets the keyboard layout for a particular input device. */ 311 virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay( 312 const InputDeviceIdentifier& identifier) = 0; 313 314 /* Gets a user-supplied alias for a particular input device, or an empty string if none. */ 315 virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier) = 0; 316 317 /* Gets the affine calibration associated with the specified device. */ 318 virtual TouchAffineTransformation getTouchAffineTransformation( 319 const String8& inputDeviceDescriptor, int32_t surfaceRotation) = 0; 320 }; 321 322 323 /* Processes raw input events and sends cooked event data to an input listener. */ 324 class InputReaderInterface : public virtual RefBase { 325 protected: 326 InputReaderInterface() { } 327 virtual ~InputReaderInterface() { } 328 329 public: 330 /* Dumps the state of the input reader. 331 * 332 * This method may be called on any thread (usually by the input manager). */ 333 virtual void dump(String8& dump) = 0; 334 335 /* Called by the heatbeat to ensures that the reader has not deadlocked. */ 336 virtual void monitor() = 0; 337 338 /* Runs a single iteration of the processing loop. 339 * Nominally reads and processes one incoming message from the EventHub. 340 * 341 * This method should be called on the input reader thread. 342 */ 343 virtual void loopOnce() = 0; 344 345 /* Gets information about all input devices. 346 * 347 * This method may be called on any thread (usually by the input manager). 348 */ 349 virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices) = 0; 350 351 /* Query current input state. */ 352 virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, 353 int32_t scanCode) = 0; 354 virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, 355 int32_t keyCode) = 0; 356 virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, 357 int32_t sw) = 0; 358 359 /* Determine whether physical keys exist for the given framework-domain key codes. */ 360 virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask, 361 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0; 362 363 /* Requests that a reconfiguration of all input devices. 364 * The changes flag is a bitfield that indicates what has changed and whether 365 * the input devices must all be reopened. */ 366 virtual void requestRefreshConfiguration(uint32_t changes) = 0; 367 368 /* Controls the vibrator of a particular input device. */ 369 virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, 370 ssize_t repeat, int32_t token) = 0; 371 virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0; 372 }; 373 374 375 /* Internal interface used by individual input devices to access global input device state 376 * and parameters maintained by the input reader. 377 */ 378 class InputReaderContext { 379 public: 380 InputReaderContext() { } 381 virtual ~InputReaderContext() { } 382 383 virtual void updateGlobalMetaState() = 0; 384 virtual int32_t getGlobalMetaState() = 0; 385 386 virtual void disableVirtualKeysUntil(nsecs_t time) = 0; 387 virtual bool shouldDropVirtualKey(nsecs_t now, 388 InputDevice* device, int32_t keyCode, int32_t scanCode) = 0; 389 390 virtual void fadePointer() = 0; 391 392 virtual void requestTimeoutAtTime(nsecs_t when) = 0; 393 virtual int32_t bumpGeneration() = 0; 394 395 virtual InputReaderPolicyInterface* getPolicy() = 0; 396 virtual InputListenerInterface* getListener() = 0; 397 virtual EventHubInterface* getEventHub() = 0; 398 }; 399 400 401 /* The input reader reads raw event data from the event hub and processes it into input events 402 * that it sends to the input listener. Some functions of the input reader, such as early 403 * event filtering in low power states, are controlled by a separate policy object. 404 * 405 * The InputReader owns a collection of InputMappers. Most of the work it does happens 406 * on the input reader thread but the InputReader can receive queries from other system 407 * components running on arbitrary threads. To keep things manageable, the InputReader 408 * uses a single Mutex to guard its state. The Mutex may be held while calling into the 409 * EventHub or the InputReaderPolicy but it is never held while calling into the 410 * InputListener. 411 */ 412 class InputReader : public InputReaderInterface { 413 public: 414 InputReader(const sp<EventHubInterface>& eventHub, 415 const sp<InputReaderPolicyInterface>& policy, 416 const sp<InputListenerInterface>& listener); 417 virtual ~InputReader(); 418 419 virtual void dump(String8& dump); 420 virtual void monitor(); 421 422 virtual void loopOnce(); 423 424 virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices); 425 426 virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, 427 int32_t scanCode); 428 virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, 429 int32_t keyCode); 430 virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, 431 int32_t sw); 432 433 virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask, 434 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags); 435 436 virtual void requestRefreshConfiguration(uint32_t changes); 437 438 virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, 439 ssize_t repeat, int32_t token); 440 virtual void cancelVibrate(int32_t deviceId, int32_t token); 441 442 protected: 443 // These members are protected so they can be instrumented by test cases. 444 virtual InputDevice* createDeviceLocked(int32_t deviceId, int32_t controllerNumber, 445 const InputDeviceIdentifier& identifier, uint32_t classes); 446 447 class ContextImpl : public InputReaderContext { 448 InputReader* mReader; 449 450 public: 451 ContextImpl(InputReader* reader); 452 453 virtual void updateGlobalMetaState(); 454 virtual int32_t getGlobalMetaState(); 455 virtual void disableVirtualKeysUntil(nsecs_t time); 456 virtual bool shouldDropVirtualKey(nsecs_t now, 457 InputDevice* device, int32_t keyCode, int32_t scanCode); 458 virtual void fadePointer(); 459 virtual void requestTimeoutAtTime(nsecs_t when); 460 virtual int32_t bumpGeneration(); 461 virtual InputReaderPolicyInterface* getPolicy(); 462 virtual InputListenerInterface* getListener(); 463 virtual EventHubInterface* getEventHub(); 464 } mContext; 465 466 friend class ContextImpl; 467 468 private: 469 Mutex mLock; 470 471 Condition mReaderIsAliveCondition; 472 473 sp<EventHubInterface> mEventHub; 474 sp<InputReaderPolicyInterface> mPolicy; 475 sp<QueuedInputListener> mQueuedListener; 476 477 InputReaderConfiguration mConfig; 478 479 // The event queue. 480 static const int EVENT_BUFFER_SIZE = 256; 481 RawEvent mEventBuffer[EVENT_BUFFER_SIZE]; 482 483 KeyedVector<int32_t, InputDevice*> mDevices; 484 485 // low-level input event decoding and device management 486 void processEventsLocked(const RawEvent* rawEvents, size_t count); 487 488 void addDeviceLocked(nsecs_t when, int32_t deviceId); 489 void removeDeviceLocked(nsecs_t when, int32_t deviceId); 490 void processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count); 491 void timeoutExpiredLocked(nsecs_t when); 492 493 void handleConfigurationChangedLocked(nsecs_t when); 494 495 int32_t mGlobalMetaState; 496 void updateGlobalMetaStateLocked(); 497 int32_t getGlobalMetaStateLocked(); 498 499 void fadePointerLocked(); 500 501 int32_t mGeneration; 502 int32_t bumpGenerationLocked(); 503 504 void getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices); 505 506 nsecs_t mDisableVirtualKeysTimeout; 507 void disableVirtualKeysUntilLocked(nsecs_t time); 508 bool shouldDropVirtualKeyLocked(nsecs_t now, 509 InputDevice* device, int32_t keyCode, int32_t scanCode); 510 511 nsecs_t mNextTimeout; 512 void requestTimeoutAtTimeLocked(nsecs_t when); 513 514 uint32_t mConfigurationChangesToRefresh; 515 void refreshConfigurationLocked(uint32_t changes); 516 517 // state queries 518 typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code); 519 int32_t getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code, 520 GetStateFunc getStateFunc); 521 bool markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes, 522 const int32_t* keyCodes, uint8_t* outFlags); 523 }; 524 525 526 /* Reads raw events from the event hub and processes them, endlessly. */ 527 class InputReaderThread : public Thread { 528 public: 529 InputReaderThread(const sp<InputReaderInterface>& reader); 530 virtual ~InputReaderThread(); 531 532 private: 533 sp<InputReaderInterface> mReader; 534 535 virtual bool threadLoop(); 536 }; 537 538 539 /* Represents the state of a single input device. */ 540 class InputDevice { 541 public: 542 InputDevice(InputReaderContext* context, int32_t id, int32_t generation, int32_t 543 controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes); 544 ~InputDevice(); 545 546 inline InputReaderContext* getContext() { return mContext; } 547 inline int32_t getId() const { return mId; } 548 inline int32_t getControllerNumber() const { return mControllerNumber; } 549 inline int32_t getGeneration() const { return mGeneration; } 550 inline const String8& getName() const { return mIdentifier.name; } 551 inline const String8& getDescriptor() { return mIdentifier.descriptor; } 552 inline uint32_t getClasses() const { return mClasses; } 553 inline uint32_t getSources() const { return mSources; } 554 555 inline bool isExternal() { return mIsExternal; } 556 inline void setExternal(bool external) { mIsExternal = external; } 557 558 inline bool isIgnored() { return mMappers.isEmpty(); } 559 560 void dump(String8& dump); 561 void addMapper(InputMapper* mapper); 562 void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 563 void reset(nsecs_t when); 564 void process(const RawEvent* rawEvents, size_t count); 565 void timeoutExpired(nsecs_t when); 566 567 void getDeviceInfo(InputDeviceInfo* outDeviceInfo); 568 int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode); 569 int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode); 570 int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode); 571 bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 572 const int32_t* keyCodes, uint8_t* outFlags); 573 void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token); 574 void cancelVibrate(int32_t token); 575 576 int32_t getMetaState(); 577 578 void fadePointer(); 579 580 void bumpGeneration(); 581 582 void notifyReset(nsecs_t when); 583 584 inline const PropertyMap& getConfiguration() { return mConfiguration; } 585 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); } 586 587 bool hasKey(int32_t code) { 588 return getEventHub()->hasScanCode(mId, code); 589 } 590 591 bool hasAbsoluteAxis(int32_t code) { 592 RawAbsoluteAxisInfo info; 593 getEventHub()->getAbsoluteAxisInfo(mId, code, &info); 594 return info.valid; 595 } 596 597 bool isKeyPressed(int32_t code) { 598 return getEventHub()->getScanCodeState(mId, code) == AKEY_STATE_DOWN; 599 } 600 601 int32_t getAbsoluteAxisValue(int32_t code) { 602 int32_t value; 603 getEventHub()->getAbsoluteAxisValue(mId, code, &value); 604 return value; 605 } 606 607 private: 608 InputReaderContext* mContext; 609 int32_t mId; 610 int32_t mGeneration; 611 int32_t mControllerNumber; 612 InputDeviceIdentifier mIdentifier; 613 String8 mAlias; 614 uint32_t mClasses; 615 616 Vector<InputMapper*> mMappers; 617 618 uint32_t mSources; 619 bool mIsExternal; 620 bool mDropUntilNextSync; 621 622 typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code); 623 int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc); 624 625 PropertyMap mConfiguration; 626 }; 627 628 629 /* Keeps track of the state of mouse or touch pad buttons. */ 630 class CursorButtonAccumulator { 631 public: 632 CursorButtonAccumulator(); 633 void reset(InputDevice* device); 634 635 void process(const RawEvent* rawEvent); 636 637 uint32_t getButtonState() const; 638 639 private: 640 bool mBtnLeft; 641 bool mBtnRight; 642 bool mBtnMiddle; 643 bool mBtnBack; 644 bool mBtnSide; 645 bool mBtnForward; 646 bool mBtnExtra; 647 bool mBtnTask; 648 649 void clearButtons(); 650 }; 651 652 653 /* Keeps track of cursor movements. */ 654 655 class CursorMotionAccumulator { 656 public: 657 CursorMotionAccumulator(); 658 void reset(InputDevice* device); 659 660 void process(const RawEvent* rawEvent); 661 void finishSync(); 662 663 inline int32_t getRelativeX() const { return mRelX; } 664 inline int32_t getRelativeY() const { return mRelY; } 665 666 private: 667 int32_t mRelX; 668 int32_t mRelY; 669 670 void clearRelativeAxes(); 671 }; 672 673 674 /* Keeps track of cursor scrolling motions. */ 675 676 class CursorScrollAccumulator { 677 public: 678 CursorScrollAccumulator(); 679 void configure(InputDevice* device); 680 void reset(InputDevice* device); 681 682 void process(const RawEvent* rawEvent); 683 void finishSync(); 684 685 inline bool haveRelativeVWheel() const { return mHaveRelWheel; } 686 inline bool haveRelativeHWheel() const { return mHaveRelHWheel; } 687 688 inline int32_t getRelativeX() const { return mRelX; } 689 inline int32_t getRelativeY() const { return mRelY; } 690 inline int32_t getRelativeVWheel() const { return mRelWheel; } 691 inline int32_t getRelativeHWheel() const { return mRelHWheel; } 692 693 private: 694 bool mHaveRelWheel; 695 bool mHaveRelHWheel; 696 697 int32_t mRelX; 698 int32_t mRelY; 699 int32_t mRelWheel; 700 int32_t mRelHWheel; 701 702 void clearRelativeAxes(); 703 }; 704 705 706 /* Keeps track of the state of touch, stylus and tool buttons. */ 707 class TouchButtonAccumulator { 708 public: 709 TouchButtonAccumulator(); 710 void configure(InputDevice* device); 711 void reset(InputDevice* device); 712 713 void process(const RawEvent* rawEvent); 714 715 uint32_t getButtonState() const; 716 int32_t getToolType() const; 717 bool isToolActive() const; 718 bool isHovering() const; 719 bool hasStylus() const; 720 721 private: 722 bool mHaveBtnTouch; 723 bool mHaveStylus; 724 725 bool mBtnTouch; 726 bool mBtnStylus; 727 bool mBtnStylus2; 728 bool mBtnToolFinger; 729 bool mBtnToolPen; 730 bool mBtnToolRubber; 731 bool mBtnToolBrush; 732 bool mBtnToolPencil; 733 bool mBtnToolAirbrush; 734 bool mBtnToolMouse; 735 bool mBtnToolLens; 736 bool mBtnToolDoubleTap; 737 bool mBtnToolTripleTap; 738 bool mBtnToolQuadTap; 739 740 void clearButtons(); 741 }; 742 743 744 /* Raw axis information from the driver. */ 745 struct RawPointerAxes { 746 RawAbsoluteAxisInfo x; 747 RawAbsoluteAxisInfo y; 748 RawAbsoluteAxisInfo pressure; 749 RawAbsoluteAxisInfo touchMajor; 750 RawAbsoluteAxisInfo touchMinor; 751 RawAbsoluteAxisInfo toolMajor; 752 RawAbsoluteAxisInfo toolMinor; 753 RawAbsoluteAxisInfo orientation; 754 RawAbsoluteAxisInfo distance; 755 RawAbsoluteAxisInfo tiltX; 756 RawAbsoluteAxisInfo tiltY; 757 RawAbsoluteAxisInfo trackingId; 758 RawAbsoluteAxisInfo slot; 759 760 RawPointerAxes(); 761 void clear(); 762 }; 763 764 765 /* Raw data for a collection of pointers including a pointer id mapping table. */ 766 struct RawPointerData { 767 struct Pointer { 768 uint32_t id; 769 int32_t x; 770 int32_t y; 771 int32_t pressure; 772 int32_t touchMajor; 773 int32_t touchMinor; 774 int32_t toolMajor; 775 int32_t toolMinor; 776 int32_t orientation; 777 int32_t distance; 778 int32_t tiltX; 779 int32_t tiltY; 780 int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant 781 bool isHovering; 782 }; 783 784 uint32_t pointerCount; 785 Pointer pointers[MAX_POINTERS]; 786 BitSet32 hoveringIdBits, touchingIdBits; 787 uint32_t idToIndex[MAX_POINTER_ID + 1]; 788 789 RawPointerData(); 790 void clear(); 791 void copyFrom(const RawPointerData& other); 792 void getCentroidOfTouchingPointers(float* outX, float* outY) const; 793 794 inline void markIdBit(uint32_t id, bool isHovering) { 795 if (isHovering) { 796 hoveringIdBits.markBit(id); 797 } else { 798 touchingIdBits.markBit(id); 799 } 800 } 801 802 inline void clearIdBits() { 803 hoveringIdBits.clear(); 804 touchingIdBits.clear(); 805 } 806 807 inline const Pointer& pointerForId(uint32_t id) const { 808 return pointers[idToIndex[id]]; 809 } 810 811 inline bool isHovering(uint32_t pointerIndex) { 812 return pointers[pointerIndex].isHovering; 813 } 814 }; 815 816 817 /* Cooked data for a collection of pointers including a pointer id mapping table. */ 818 struct CookedPointerData { 819 uint32_t pointerCount; 820 PointerProperties pointerProperties[MAX_POINTERS]; 821 PointerCoords pointerCoords[MAX_POINTERS]; 822 BitSet32 hoveringIdBits, touchingIdBits; 823 uint32_t idToIndex[MAX_POINTER_ID + 1]; 824 825 CookedPointerData(); 826 void clear(); 827 void copyFrom(const CookedPointerData& other); 828 829 inline const PointerCoords& pointerCoordsForId(uint32_t id) const { 830 return pointerCoords[idToIndex[id]]; 831 } 832 833 inline bool isHovering(uint32_t pointerIndex) { 834 return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id); 835 } 836 }; 837 838 839 /* Keeps track of the state of single-touch protocol. */ 840 class SingleTouchMotionAccumulator { 841 public: 842 SingleTouchMotionAccumulator(); 843 844 void process(const RawEvent* rawEvent); 845 void reset(InputDevice* device); 846 847 inline int32_t getAbsoluteX() const { return mAbsX; } 848 inline int32_t getAbsoluteY() const { return mAbsY; } 849 inline int32_t getAbsolutePressure() const { return mAbsPressure; } 850 inline int32_t getAbsoluteToolWidth() const { return mAbsToolWidth; } 851 inline int32_t getAbsoluteDistance() const { return mAbsDistance; } 852 inline int32_t getAbsoluteTiltX() const { return mAbsTiltX; } 853 inline int32_t getAbsoluteTiltY() const { return mAbsTiltY; } 854 855 private: 856 int32_t mAbsX; 857 int32_t mAbsY; 858 int32_t mAbsPressure; 859 int32_t mAbsToolWidth; 860 int32_t mAbsDistance; 861 int32_t mAbsTiltX; 862 int32_t mAbsTiltY; 863 864 void clearAbsoluteAxes(); 865 }; 866 867 868 /* Keeps track of the state of multi-touch protocol. */ 869 class MultiTouchMotionAccumulator { 870 public: 871 class Slot { 872 public: 873 inline bool isInUse() const { return mInUse; } 874 inline int32_t getX() const { return mAbsMTPositionX; } 875 inline int32_t getY() const { return mAbsMTPositionY; } 876 inline int32_t getTouchMajor() const { return mAbsMTTouchMajor; } 877 inline int32_t getTouchMinor() const { 878 return mHaveAbsMTTouchMinor ? mAbsMTTouchMinor : mAbsMTTouchMajor; } 879 inline int32_t getToolMajor() const { return mAbsMTWidthMajor; } 880 inline int32_t getToolMinor() const { 881 return mHaveAbsMTWidthMinor ? mAbsMTWidthMinor : mAbsMTWidthMajor; } 882 inline int32_t getOrientation() const { return mAbsMTOrientation; } 883 inline int32_t getTrackingId() const { return mAbsMTTrackingId; } 884 inline int32_t getPressure() const { return mAbsMTPressure; } 885 inline int32_t getDistance() const { return mAbsMTDistance; } 886 inline int32_t getToolType() const; 887 888 private: 889 friend class MultiTouchMotionAccumulator; 890 891 bool mInUse; 892 bool mHaveAbsMTTouchMinor; 893 bool mHaveAbsMTWidthMinor; 894 bool mHaveAbsMTToolType; 895 896 int32_t mAbsMTPositionX; 897 int32_t mAbsMTPositionY; 898 int32_t mAbsMTTouchMajor; 899 int32_t mAbsMTTouchMinor; 900 int32_t mAbsMTWidthMajor; 901 int32_t mAbsMTWidthMinor; 902 int32_t mAbsMTOrientation; 903 int32_t mAbsMTTrackingId; 904 int32_t mAbsMTPressure; 905 int32_t mAbsMTDistance; 906 int32_t mAbsMTToolType; 907 908 Slot(); 909 void clear(); 910 }; 911 912 MultiTouchMotionAccumulator(); 913 ~MultiTouchMotionAccumulator(); 914 915 void configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol); 916 void reset(InputDevice* device); 917 void process(const RawEvent* rawEvent); 918 void finishSync(); 919 bool hasStylus() const; 920 921 inline size_t getSlotCount() const { return mSlotCount; } 922 inline const Slot* getSlot(size_t index) const { return &mSlots[index]; } 923 924 private: 925 int32_t mCurrentSlot; 926 Slot* mSlots; 927 size_t mSlotCount; 928 bool mUsingSlotsProtocol; 929 bool mHaveStylus; 930 931 void clearSlots(int32_t initialSlot); 932 }; 933 934 935 /* An input mapper transforms raw input events into cooked event data. 936 * A single input device can have multiple associated input mappers in order to interpret 937 * different classes of events. 938 * 939 * InputMapper lifecycle: 940 * - create 941 * - configure with 0 changes 942 * - reset 943 * - process, process, process (may occasionally reconfigure with non-zero changes or reset) 944 * - reset 945 * - destroy 946 */ 947 class InputMapper { 948 public: 949 InputMapper(InputDevice* device); 950 virtual ~InputMapper(); 951 952 inline InputDevice* getDevice() { return mDevice; } 953 inline int32_t getDeviceId() { return mDevice->getId(); } 954 inline const String8 getDeviceName() { return mDevice->getName(); } 955 inline InputReaderContext* getContext() { return mContext; } 956 inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); } 957 inline InputListenerInterface* getListener() { return mContext->getListener(); } 958 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); } 959 960 virtual uint32_t getSources() = 0; 961 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 962 virtual void dump(String8& dump); 963 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 964 virtual void reset(nsecs_t when); 965 virtual void process(const RawEvent* rawEvent) = 0; 966 virtual void timeoutExpired(nsecs_t when); 967 968 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode); 969 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode); 970 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode); 971 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 972 const int32_t* keyCodes, uint8_t* outFlags); 973 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, 974 int32_t token); 975 virtual void cancelVibrate(int32_t token); 976 977 virtual int32_t getMetaState(); 978 979 virtual void fadePointer(); 980 981 protected: 982 InputDevice* mDevice; 983 InputReaderContext* mContext; 984 985 status_t getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo); 986 void bumpGeneration(); 987 988 static void dumpRawAbsoluteAxisInfo(String8& dump, 989 const RawAbsoluteAxisInfo& axis, const char* name); 990 }; 991 992 993 class SwitchInputMapper : public InputMapper { 994 public: 995 SwitchInputMapper(InputDevice* device); 996 virtual ~SwitchInputMapper(); 997 998 virtual uint32_t getSources(); 999 virtual void process(const RawEvent* rawEvent); 1000 1001 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode); 1002 virtual void dump(String8& dump); 1003 1004 private: 1005 uint32_t mSwitchValues; 1006 uint32_t mUpdatedSwitchMask; 1007 1008 void processSwitch(int32_t switchCode, int32_t switchValue); 1009 void sync(nsecs_t when); 1010 }; 1011 1012 1013 class VibratorInputMapper : public InputMapper { 1014 public: 1015 VibratorInputMapper(InputDevice* device); 1016 virtual ~VibratorInputMapper(); 1017 1018 virtual uint32_t getSources(); 1019 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 1020 virtual void process(const RawEvent* rawEvent); 1021 1022 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, 1023 int32_t token); 1024 virtual void cancelVibrate(int32_t token); 1025 virtual void timeoutExpired(nsecs_t when); 1026 virtual void dump(String8& dump); 1027 1028 private: 1029 bool mVibrating; 1030 nsecs_t mPattern[MAX_VIBRATE_PATTERN_SIZE]; 1031 size_t mPatternSize; 1032 ssize_t mRepeat; 1033 int32_t mToken; 1034 ssize_t mIndex; 1035 nsecs_t mNextStepTime; 1036 1037 void nextStep(); 1038 void stopVibrating(); 1039 }; 1040 1041 1042 class KeyboardInputMapper : public InputMapper { 1043 public: 1044 KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType); 1045 virtual ~KeyboardInputMapper(); 1046 1047 virtual uint32_t getSources(); 1048 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 1049 virtual void dump(String8& dump); 1050 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 1051 virtual void reset(nsecs_t when); 1052 virtual void process(const RawEvent* rawEvent); 1053 1054 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode); 1055 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode); 1056 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1057 const int32_t* keyCodes, uint8_t* outFlags); 1058 1059 virtual int32_t getMetaState(); 1060 1061 private: 1062 struct KeyDown { 1063 int32_t keyCode; 1064 int32_t scanCode; 1065 }; 1066 1067 uint32_t mSource; 1068 int32_t mKeyboardType; 1069 1070 int32_t mOrientation; // orientation for dpad keys 1071 1072 Vector<KeyDown> mKeyDowns; // keys that are down 1073 int32_t mMetaState; 1074 nsecs_t mDownTime; // time of most recent key down 1075 1076 int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none 1077 1078 struct LedState { 1079 bool avail; // led is available 1080 bool on; // we think the led is currently on 1081 }; 1082 LedState mCapsLockLedState; 1083 LedState mNumLockLedState; 1084 LedState mScrollLockLedState; 1085 1086 // Immutable configuration parameters. 1087 struct Parameters { 1088 bool hasAssociatedDisplay; 1089 bool orientationAware; 1090 bool handlesKeyRepeat; 1091 } mParameters; 1092 1093 void configureParameters(); 1094 void dumpParameters(String8& dump); 1095 1096 bool isKeyboardOrGamepadKey(int32_t scanCode); 1097 1098 void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode, 1099 uint32_t policyFlags); 1100 1101 ssize_t findKeyDown(int32_t scanCode); 1102 1103 void resetLedState(); 1104 void initializeLedState(LedState& ledState, int32_t led); 1105 void updateLedState(bool reset); 1106 void updateLedStateForModifier(LedState& ledState, int32_t led, 1107 int32_t modifier, bool reset); 1108 }; 1109 1110 1111 class CursorInputMapper : public InputMapper { 1112 public: 1113 CursorInputMapper(InputDevice* device); 1114 virtual ~CursorInputMapper(); 1115 1116 virtual uint32_t getSources(); 1117 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 1118 virtual void dump(String8& dump); 1119 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 1120 virtual void reset(nsecs_t when); 1121 virtual void process(const RawEvent* rawEvent); 1122 1123 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode); 1124 1125 virtual void fadePointer(); 1126 1127 private: 1128 // Amount that trackball needs to move in order to generate a key event. 1129 static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6; 1130 1131 // Immutable configuration parameters. 1132 struct Parameters { 1133 enum Mode { 1134 MODE_POINTER, 1135 MODE_NAVIGATION, 1136 }; 1137 1138 Mode mode; 1139 bool hasAssociatedDisplay; 1140 bool orientationAware; 1141 } mParameters; 1142 1143 CursorButtonAccumulator mCursorButtonAccumulator; 1144 CursorMotionAccumulator mCursorMotionAccumulator; 1145 CursorScrollAccumulator mCursorScrollAccumulator; 1146 1147 int32_t mSource; 1148 float mXScale; 1149 float mYScale; 1150 float mXPrecision; 1151 float mYPrecision; 1152 1153 float mVWheelScale; 1154 float mHWheelScale; 1155 1156 // Velocity controls for mouse pointer and wheel movements. 1157 // The controls for X and Y wheel movements are separate to keep them decoupled. 1158 VelocityControl mPointerVelocityControl; 1159 VelocityControl mWheelXVelocityControl; 1160 VelocityControl mWheelYVelocityControl; 1161 1162 int32_t mOrientation; 1163 1164 sp<PointerControllerInterface> mPointerController; 1165 1166 int32_t mButtonState; 1167 nsecs_t mDownTime; 1168 1169 void configureParameters(); 1170 void dumpParameters(String8& dump); 1171 1172 void sync(nsecs_t when); 1173 }; 1174 1175 1176 class TouchInputMapper : public InputMapper { 1177 public: 1178 TouchInputMapper(InputDevice* device); 1179 virtual ~TouchInputMapper(); 1180 1181 virtual uint32_t getSources(); 1182 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 1183 virtual void dump(String8& dump); 1184 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 1185 virtual void reset(nsecs_t when); 1186 virtual void process(const RawEvent* rawEvent); 1187 1188 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode); 1189 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode); 1190 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, 1191 const int32_t* keyCodes, uint8_t* outFlags); 1192 1193 virtual void fadePointer(); 1194 virtual void timeoutExpired(nsecs_t when); 1195 1196 protected: 1197 CursorButtonAccumulator mCursorButtonAccumulator; 1198 CursorScrollAccumulator mCursorScrollAccumulator; 1199 TouchButtonAccumulator mTouchButtonAccumulator; 1200 1201 struct VirtualKey { 1202 int32_t keyCode; 1203 int32_t scanCode; 1204 uint32_t flags; 1205 1206 // computed hit box, specified in touch screen coords based on known display size 1207 int32_t hitLeft; 1208 int32_t hitTop; 1209 int32_t hitRight; 1210 int32_t hitBottom; 1211 1212 inline bool isHit(int32_t x, int32_t y) const { 1213 return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom; 1214 } 1215 }; 1216 1217 // Input sources and device mode. 1218 uint32_t mSource; 1219 1220 enum DeviceMode { 1221 DEVICE_MODE_DISABLED, // input is disabled 1222 DEVICE_MODE_DIRECT, // direct mapping (touchscreen) 1223 DEVICE_MODE_UNSCALED, // unscaled mapping (touchpad) 1224 DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation) 1225 DEVICE_MODE_POINTER, // pointer mapping (pointer) 1226 }; 1227 DeviceMode mDeviceMode; 1228 1229 // The reader's configuration. 1230 InputReaderConfiguration mConfig; 1231 1232 // Immutable configuration parameters. 1233 struct Parameters { 1234 enum DeviceType { 1235 DEVICE_TYPE_TOUCH_SCREEN, 1236 DEVICE_TYPE_TOUCH_PAD, 1237 DEVICE_TYPE_TOUCH_NAVIGATION, 1238 DEVICE_TYPE_POINTER, 1239 }; 1240 1241 DeviceType deviceType; 1242 bool hasAssociatedDisplay; 1243 bool associatedDisplayIsExternal; 1244 bool orientationAware; 1245 bool hasButtonUnderPad; 1246 1247 enum GestureMode { 1248 GESTURE_MODE_POINTER, 1249 GESTURE_MODE_SPOTS, 1250 }; 1251 GestureMode gestureMode; 1252 1253 bool wake; 1254 } mParameters; 1255 1256 // Immutable calibration parameters in parsed form. 1257 struct Calibration { 1258 // Size 1259 enum SizeCalibration { 1260 SIZE_CALIBRATION_DEFAULT, 1261 SIZE_CALIBRATION_NONE, 1262 SIZE_CALIBRATION_GEOMETRIC, 1263 SIZE_CALIBRATION_DIAMETER, 1264 SIZE_CALIBRATION_BOX, 1265 SIZE_CALIBRATION_AREA, 1266 }; 1267 1268 SizeCalibration sizeCalibration; 1269 1270 bool haveSizeScale; 1271 float sizeScale; 1272 bool haveSizeBias; 1273 float sizeBias; 1274 bool haveSizeIsSummed; 1275 bool sizeIsSummed; 1276 1277 // Pressure 1278 enum PressureCalibration { 1279 PRESSURE_CALIBRATION_DEFAULT, 1280 PRESSURE_CALIBRATION_NONE, 1281 PRESSURE_CALIBRATION_PHYSICAL, 1282 PRESSURE_CALIBRATION_AMPLITUDE, 1283 }; 1284 1285 PressureCalibration pressureCalibration; 1286 bool havePressureScale; 1287 float pressureScale; 1288 1289 // Orientation 1290 enum OrientationCalibration { 1291 ORIENTATION_CALIBRATION_DEFAULT, 1292 ORIENTATION_CALIBRATION_NONE, 1293 ORIENTATION_CALIBRATION_INTERPOLATED, 1294 ORIENTATION_CALIBRATION_VECTOR, 1295 }; 1296 1297 OrientationCalibration orientationCalibration; 1298 1299 // Distance 1300 enum DistanceCalibration { 1301 DISTANCE_CALIBRATION_DEFAULT, 1302 DISTANCE_CALIBRATION_NONE, 1303 DISTANCE_CALIBRATION_SCALED, 1304 }; 1305 1306 DistanceCalibration distanceCalibration; 1307 bool haveDistanceScale; 1308 float distanceScale; 1309 1310 enum CoverageCalibration { 1311 COVERAGE_CALIBRATION_DEFAULT, 1312 COVERAGE_CALIBRATION_NONE, 1313 COVERAGE_CALIBRATION_BOX, 1314 }; 1315 1316 CoverageCalibration coverageCalibration; 1317 1318 inline void applySizeScaleAndBias(float* outSize) const { 1319 if (haveSizeScale) { 1320 *outSize *= sizeScale; 1321 } 1322 if (haveSizeBias) { 1323 *outSize += sizeBias; 1324 } 1325 if (*outSize < 0) { 1326 *outSize = 0; 1327 } 1328 } 1329 } mCalibration; 1330 1331 // Affine location transformation/calibration 1332 struct TouchAffineTransformation mAffineTransform; 1333 1334 // Raw pointer axis information from the driver. 1335 RawPointerAxes mRawPointerAxes; 1336 1337 // Raw pointer sample data. 1338 RawPointerData mCurrentRawPointerData; 1339 RawPointerData mLastRawPointerData; 1340 1341 // Cooked pointer sample data. 1342 CookedPointerData mCurrentCookedPointerData; 1343 CookedPointerData mLastCookedPointerData; 1344 1345 // Button state. 1346 int32_t mCurrentButtonState; 1347 int32_t mLastButtonState; 1348 1349 // Scroll state. 1350 int32_t mCurrentRawVScroll; 1351 int32_t mCurrentRawHScroll; 1352 1353 // Id bits used to differentiate fingers, stylus and mouse tools. 1354 BitSet32 mCurrentFingerIdBits; // finger or unknown 1355 BitSet32 mLastFingerIdBits; 1356 BitSet32 mCurrentStylusIdBits; // stylus or eraser 1357 BitSet32 mLastStylusIdBits; 1358 BitSet32 mCurrentMouseIdBits; // mouse or lens 1359 BitSet32 mLastMouseIdBits; 1360 1361 // True if we sent a HOVER_ENTER event. 1362 bool mSentHoverEnter; 1363 1364 // The time the primary pointer last went down. 1365 nsecs_t mDownTime; 1366 1367 // The pointer controller, or null if the device is not a pointer. 1368 sp<PointerControllerInterface> mPointerController; 1369 1370 Vector<VirtualKey> mVirtualKeys; 1371 1372 virtual void configureParameters(); 1373 virtual void dumpParameters(String8& dump); 1374 virtual void configureRawPointerAxes(); 1375 virtual void dumpRawPointerAxes(String8& dump); 1376 virtual void configureSurface(nsecs_t when, bool* outResetNeeded); 1377 virtual void dumpSurface(String8& dump); 1378 virtual void configureVirtualKeys(); 1379 virtual void dumpVirtualKeys(String8& dump); 1380 virtual void parseCalibration(); 1381 virtual void resolveCalibration(); 1382 virtual void dumpCalibration(String8& dump); 1383 virtual void dumpAffineTransformation(String8& dump); 1384 virtual bool hasStylus() const = 0; 1385 virtual void updateAffineTransformation(); 1386 1387 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds) = 0; 1388 1389 private: 1390 // The current viewport. 1391 // The components of the viewport are specified in the display's rotated orientation. 1392 DisplayViewport mViewport; 1393 1394 // The surface orientation, width and height set by configureSurface(). 1395 // The width and height are derived from the viewport but are specified 1396 // in the natural orientation. 1397 // The surface origin specifies how the surface coordinates should be translated 1398 // to align with the logical display coordinate space. 1399 // The orientation may be different from the viewport orientation as it specifies 1400 // the rotation of the surface coordinates required to produce the viewport's 1401 // requested orientation, so it will depend on whether the device is orientation aware. 1402 int32_t mSurfaceWidth; 1403 int32_t mSurfaceHeight; 1404 int32_t mSurfaceLeft; 1405 int32_t mSurfaceTop; 1406 int32_t mSurfaceOrientation; 1407 1408 // Translation and scaling factors, orientation-independent. 1409 float mXTranslate; 1410 float mXScale; 1411 float mXPrecision; 1412 1413 float mYTranslate; 1414 float mYScale; 1415 float mYPrecision; 1416 1417 float mGeometricScale; 1418 1419 float mPressureScale; 1420 1421 float mSizeScale; 1422 1423 float mOrientationScale; 1424 1425 float mDistanceScale; 1426 1427 bool mHaveTilt; 1428 float mTiltXCenter; 1429 float mTiltXScale; 1430 float mTiltYCenter; 1431 float mTiltYScale; 1432 1433 // Oriented motion ranges for input device info. 1434 struct OrientedRanges { 1435 InputDeviceInfo::MotionRange x; 1436 InputDeviceInfo::MotionRange y; 1437 InputDeviceInfo::MotionRange pressure; 1438 1439 bool haveSize; 1440 InputDeviceInfo::MotionRange size; 1441 1442 bool haveTouchSize; 1443 InputDeviceInfo::MotionRange touchMajor; 1444 InputDeviceInfo::MotionRange touchMinor; 1445 1446 bool haveToolSize; 1447 InputDeviceInfo::MotionRange toolMajor; 1448 InputDeviceInfo::MotionRange toolMinor; 1449 1450 bool haveOrientation; 1451 InputDeviceInfo::MotionRange orientation; 1452 1453 bool haveDistance; 1454 InputDeviceInfo::MotionRange distance; 1455 1456 bool haveTilt; 1457 InputDeviceInfo::MotionRange tilt; 1458 1459 OrientedRanges() { 1460 clear(); 1461 } 1462 1463 void clear() { 1464 haveSize = false; 1465 haveTouchSize = false; 1466 haveToolSize = false; 1467 haveOrientation = false; 1468 haveDistance = false; 1469 haveTilt = false; 1470 } 1471 } mOrientedRanges; 1472 1473 // Oriented dimensions and precision. 1474 float mOrientedXPrecision; 1475 float mOrientedYPrecision; 1476 1477 struct CurrentVirtualKeyState { 1478 bool down; 1479 bool ignored; 1480 nsecs_t downTime; 1481 int32_t keyCode; 1482 int32_t scanCode; 1483 } mCurrentVirtualKey; 1484 1485 // Scale factor for gesture or mouse based pointer movements. 1486 float mPointerXMovementScale; 1487 float mPointerYMovementScale; 1488 1489 // Scale factor for gesture based zooming and other freeform motions. 1490 float mPointerXZoomScale; 1491 float mPointerYZoomScale; 1492 1493 // The maximum swipe width. 1494 float mPointerGestureMaxSwipeWidth; 1495 1496 struct PointerDistanceHeapElement { 1497 uint32_t currentPointerIndex : 8; 1498 uint32_t lastPointerIndex : 8; 1499 uint64_t distance : 48; // squared distance 1500 }; 1501 1502 enum PointerUsage { 1503 POINTER_USAGE_NONE, 1504 POINTER_USAGE_GESTURES, 1505 POINTER_USAGE_STYLUS, 1506 POINTER_USAGE_MOUSE, 1507 }; 1508 PointerUsage mPointerUsage; 1509 1510 struct PointerGesture { 1511 enum Mode { 1512 // No fingers, button is not pressed. 1513 // Nothing happening. 1514 NEUTRAL, 1515 1516 // No fingers, button is not pressed. 1517 // Tap detected. 1518 // Emits DOWN and UP events at the pointer location. 1519 TAP, 1520 1521 // Exactly one finger dragging following a tap. 1522 // Pointer follows the active finger. 1523 // Emits DOWN, MOVE and UP events at the pointer location. 1524 // 1525 // Detect double-taps when the finger goes up while in TAP_DRAG mode. 1526 TAP_DRAG, 1527 1528 // Button is pressed. 1529 // Pointer follows the active finger if there is one. Other fingers are ignored. 1530 // Emits DOWN, MOVE and UP events at the pointer location. 1531 BUTTON_CLICK_OR_DRAG, 1532 1533 // Exactly one finger, button is not pressed. 1534 // Pointer follows the active finger. 1535 // Emits HOVER_MOVE events at the pointer location. 1536 // 1537 // Detect taps when the finger goes up while in HOVER mode. 1538 HOVER, 1539 1540 // Exactly two fingers but neither have moved enough to clearly indicate 1541 // whether a swipe or freeform gesture was intended. We consider the 1542 // pointer to be pressed so this enables clicking or long-pressing on buttons. 1543 // Pointer does not move. 1544 // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate. 1545 PRESS, 1546 1547 // Exactly two fingers moving in the same direction, button is not pressed. 1548 // Pointer does not move. 1549 // Emits DOWN, MOVE and UP events with a single pointer coordinate that 1550 // follows the midpoint between both fingers. 1551 SWIPE, 1552 1553 // Two or more fingers moving in arbitrary directions, button is not pressed. 1554 // Pointer does not move. 1555 // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow 1556 // each finger individually relative to the initial centroid of the finger. 1557 FREEFORM, 1558 1559 // Waiting for quiet time to end before starting the next gesture. 1560 QUIET, 1561 }; 1562 1563 // Time the first finger went down. 1564 nsecs_t firstTouchTime; 1565 1566 // The active pointer id from the raw touch data. 1567 int32_t activeTouchId; // -1 if none 1568 1569 // The active pointer id from the gesture last delivered to the application. 1570 int32_t activeGestureId; // -1 if none 1571 1572 // Pointer coords and ids for the current and previous pointer gesture. 1573 Mode currentGestureMode; 1574 BitSet32 currentGestureIdBits; 1575 uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1]; 1576 PointerProperties currentGestureProperties[MAX_POINTERS]; 1577 PointerCoords currentGestureCoords[MAX_POINTERS]; 1578 1579 Mode lastGestureMode; 1580 BitSet32 lastGestureIdBits; 1581 uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1]; 1582 PointerProperties lastGestureProperties[MAX_POINTERS]; 1583 PointerCoords lastGestureCoords[MAX_POINTERS]; 1584 1585 // Time the pointer gesture last went down. 1586 nsecs_t downTime; 1587 1588 // Time when the pointer went down for a TAP. 1589 nsecs_t tapDownTime; 1590 1591 // Time when the pointer went up for a TAP. 1592 nsecs_t tapUpTime; 1593 1594 // Location of initial tap. 1595 float tapX, tapY; 1596 1597 // Time we started waiting for quiescence. 1598 nsecs_t quietTime; 1599 1600 // Reference points for multitouch gestures. 1601 float referenceTouchX; // reference touch X/Y coordinates in surface units 1602 float referenceTouchY; 1603 float referenceGestureX; // reference gesture X/Y coordinates in pixels 1604 float referenceGestureY; 1605 1606 // Distance that each pointer has traveled which has not yet been 1607 // subsumed into the reference gesture position. 1608 BitSet32 referenceIdBits; 1609 struct Delta { 1610 float dx, dy; 1611 }; 1612 Delta referenceDeltas[MAX_POINTER_ID + 1]; 1613 1614 // Describes how touch ids are mapped to gesture ids for freeform gestures. 1615 uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1]; 1616 1617 // A velocity tracker for determining whether to switch active pointers during drags. 1618 VelocityTracker velocityTracker; 1619 1620 void reset() { 1621 firstTouchTime = LLONG_MIN; 1622 activeTouchId = -1; 1623 activeGestureId = -1; 1624 currentGestureMode = NEUTRAL; 1625 currentGestureIdBits.clear(); 1626 lastGestureMode = NEUTRAL; 1627 lastGestureIdBits.clear(); 1628 downTime = 0; 1629 velocityTracker.clear(); 1630 resetTap(); 1631 resetQuietTime(); 1632 } 1633 1634 void resetTap() { 1635 tapDownTime = LLONG_MIN; 1636 tapUpTime = LLONG_MIN; 1637 } 1638 1639 void resetQuietTime() { 1640 quietTime = LLONG_MIN; 1641 } 1642 } mPointerGesture; 1643 1644 struct PointerSimple { 1645 PointerCoords currentCoords; 1646 PointerProperties currentProperties; 1647 PointerCoords lastCoords; 1648 PointerProperties lastProperties; 1649 1650 // True if the pointer is down. 1651 bool down; 1652 1653 // True if the pointer is hovering. 1654 bool hovering; 1655 1656 // Time the pointer last went down. 1657 nsecs_t downTime; 1658 1659 void reset() { 1660 currentCoords.clear(); 1661 currentProperties.clear(); 1662 lastCoords.clear(); 1663 lastProperties.clear(); 1664 down = false; 1665 hovering = false; 1666 downTime = 0; 1667 } 1668 } mPointerSimple; 1669 1670 // The pointer and scroll velocity controls. 1671 VelocityControl mPointerVelocityControl; 1672 VelocityControl mWheelXVelocityControl; 1673 VelocityControl mWheelYVelocityControl; 1674 1675 void sync(nsecs_t when); 1676 1677 bool consumeRawTouches(nsecs_t when, uint32_t policyFlags); 1678 void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, 1679 int32_t keyEventAction, int32_t keyEventFlags); 1680 1681 void dispatchTouches(nsecs_t when, uint32_t policyFlags); 1682 void dispatchHoverExit(nsecs_t when, uint32_t policyFlags); 1683 void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags); 1684 void cookPointerData(); 1685 1686 void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage); 1687 void abortPointerUsage(nsecs_t when, uint32_t policyFlags); 1688 1689 void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout); 1690 void abortPointerGestures(nsecs_t when, uint32_t policyFlags); 1691 bool preparePointerGestures(nsecs_t when, 1692 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, 1693 bool isTimeout); 1694 1695 void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags); 1696 void abortPointerStylus(nsecs_t when, uint32_t policyFlags); 1697 1698 void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags); 1699 void abortPointerMouse(nsecs_t when, uint32_t policyFlags); 1700 1701 void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, 1702 bool down, bool hovering); 1703 void abortPointerSimple(nsecs_t when, uint32_t policyFlags); 1704 1705 // Dispatches a motion event. 1706 // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the 1707 // method will take care of setting the index and transmuting the action to DOWN or UP 1708 // it is the first / last pointer to go down / up. 1709 void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, 1710 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState, 1711 int32_t edgeFlags, 1712 const PointerProperties* properties, const PointerCoords* coords, 1713 const uint32_t* idToIndex, BitSet32 idBits, 1714 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime); 1715 1716 // Updates pointer coords and properties for pointers with specified ids that have moved. 1717 // Returns true if any of them changed. 1718 bool updateMovedPointers(const PointerProperties* inProperties, 1719 const PointerCoords* inCoords, const uint32_t* inIdToIndex, 1720 PointerProperties* outProperties, PointerCoords* outCoords, 1721 const uint32_t* outIdToIndex, BitSet32 idBits) const; 1722 1723 bool isPointInsideSurface(int32_t x, int32_t y); 1724 const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y); 1725 1726 void assignPointerIds(); 1727 }; 1728 1729 1730 class SingleTouchInputMapper : public TouchInputMapper { 1731 public: 1732 SingleTouchInputMapper(InputDevice* device); 1733 virtual ~SingleTouchInputMapper(); 1734 1735 virtual void reset(nsecs_t when); 1736 virtual void process(const RawEvent* rawEvent); 1737 1738 protected: 1739 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds); 1740 virtual void configureRawPointerAxes(); 1741 virtual bool hasStylus() const; 1742 1743 private: 1744 SingleTouchMotionAccumulator mSingleTouchMotionAccumulator; 1745 }; 1746 1747 1748 class MultiTouchInputMapper : public TouchInputMapper { 1749 public: 1750 MultiTouchInputMapper(InputDevice* device); 1751 virtual ~MultiTouchInputMapper(); 1752 1753 virtual void reset(nsecs_t when); 1754 virtual void process(const RawEvent* rawEvent); 1755 1756 protected: 1757 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds); 1758 virtual void configureRawPointerAxes(); 1759 virtual bool hasStylus() const; 1760 1761 private: 1762 MultiTouchMotionAccumulator mMultiTouchMotionAccumulator; 1763 1764 // Specifies the pointer id bits that are in use, and their associated tracking id. 1765 BitSet32 mPointerIdBits; 1766 int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1]; 1767 }; 1768 1769 1770 class JoystickInputMapper : public InputMapper { 1771 public: 1772 JoystickInputMapper(InputDevice* device); 1773 virtual ~JoystickInputMapper(); 1774 1775 virtual uint32_t getSources(); 1776 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo); 1777 virtual void dump(String8& dump); 1778 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes); 1779 virtual void reset(nsecs_t when); 1780 virtual void process(const RawEvent* rawEvent); 1781 1782 private: 1783 struct Axis { 1784 RawAbsoluteAxisInfo rawAxisInfo; 1785 AxisInfo axisInfo; 1786 1787 bool explicitlyMapped; // true if the axis was explicitly assigned an axis id 1788 1789 float scale; // scale factor from raw to normalized values 1790 float offset; // offset to add after scaling for normalization 1791 float highScale; // scale factor from raw to normalized values of high split 1792 float highOffset; // offset to add after scaling for normalization of high split 1793 1794 float min; // normalized inclusive minimum 1795 float max; // normalized inclusive maximum 1796 float flat; // normalized flat region size 1797 float fuzz; // normalized error tolerance 1798 float resolution; // normalized resolution in units/mm 1799 1800 float filter; // filter out small variations of this size 1801 float currentValue; // current value 1802 float newValue; // most recent value 1803 float highCurrentValue; // current value of high split 1804 float highNewValue; // most recent value of high split 1805 1806 void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo, 1807 bool explicitlyMapped, float scale, float offset, 1808 float highScale, float highOffset, 1809 float min, float max, float flat, float fuzz, float resolution) { 1810 this->rawAxisInfo = rawAxisInfo; 1811 this->axisInfo = axisInfo; 1812 this->explicitlyMapped = explicitlyMapped; 1813 this->scale = scale; 1814 this->offset = offset; 1815 this->highScale = highScale; 1816 this->highOffset = highOffset; 1817 this->min = min; 1818 this->max = max; 1819 this->flat = flat; 1820 this->fuzz = fuzz; 1821 this->resolution = resolution; 1822 this->filter = 0; 1823 resetValue(); 1824 } 1825 1826 void resetValue() { 1827 this->currentValue = 0; 1828 this->newValue = 0; 1829 this->highCurrentValue = 0; 1830 this->highNewValue = 0; 1831 } 1832 }; 1833 1834 // Axes indexed by raw ABS_* axis index. 1835 KeyedVector<int32_t, Axis> mAxes; 1836 1837 void sync(nsecs_t when, bool force); 1838 1839 bool haveAxis(int32_t axisId); 1840 void pruneAxes(bool ignoreExplicitlyMappedAxes); 1841 bool filterAxes(bool force); 1842 1843 static bool hasValueChangedSignificantly(float filter, 1844 float newValue, float currentValue, float min, float max); 1845 static bool hasMovedNearerToValueWithinFilteredRange(float filter, 1846 float newValue, float currentValue, float thresholdValue); 1847 1848 static bool isCenteredAxis(int32_t axis); 1849 static int32_t getCompatAxis(int32_t axis); 1850 1851 static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info); 1852 static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis, 1853 float value); 1854 }; 1855 1856 } // namespace android 1857 1858 #endif // _UI_INPUT_READER_H 1859