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