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