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