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