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