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