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