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