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