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