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