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