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