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