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