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