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