InputReader.h revision 80fd47ce75253dcdc2cfa85d7a3f42634b923a47
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    // The event queue.
220    static const int EVENT_BUFFER_SIZE = 256;
221    RawEvent mEventBuffer[EVENT_BUFFER_SIZE];
222
223    // This reader/writer lock guards the list of input devices.
224    // The writer lock must be held whenever the list of input devices is modified
225    //   and then promptly released.
226    // The reader lock must be held whenever the list of input devices is traversed or an
227    //   input device in the list is accessed.
228    // This lock only protects the registry and prevents inadvertent deletion of device objects
229    // that are in use.  Individual devices are responsible for guarding their own internal state
230    // as needed for concurrent operation.
231    RWLock mDeviceRegistryLock;
232    KeyedVector<int32_t, InputDevice*> mDevices;
233
234    // low-level input event decoding and device management
235    void processEvents(const RawEvent* rawEvents, size_t count);
236
237    void addDevice(int32_t deviceId);
238    void removeDevice(int32_t deviceId);
239    void processEventsForDevice(int32_t deviceId, const RawEvent* rawEvents, size_t count);
240    void timeoutExpired(nsecs_t when);
241
242    void handleConfigurationChanged(nsecs_t when);
243    void configureExcludedDevices();
244
245    // state management for all devices
246    Mutex mStateLock;
247
248    int32_t mGlobalMetaState;
249    virtual void updateGlobalMetaState();
250    virtual int32_t getGlobalMetaState();
251
252    virtual void fadePointer();
253
254    InputConfiguration mInputConfiguration;
255    void updateInputConfiguration();
256
257    nsecs_t mDisableVirtualKeysTimeout; // only accessed by reader thread
258    virtual void disableVirtualKeysUntil(nsecs_t time);
259    virtual bool shouldDropVirtualKey(nsecs_t now,
260            InputDevice* device, int32_t keyCode, int32_t scanCode);
261
262    nsecs_t mNextTimeout; // only accessed by reader thread
263    virtual void requestTimeoutAtTime(nsecs_t when);
264
265    // state queries
266    typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
267    int32_t getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
268            GetStateFunc getStateFunc);
269    bool markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
270            const int32_t* keyCodes, uint8_t* outFlags);
271};
272
273
274/* Reads raw events from the event hub and processes them, endlessly. */
275class InputReaderThread : public Thread {
276public:
277    InputReaderThread(const sp<InputReaderInterface>& reader);
278    virtual ~InputReaderThread();
279
280private:
281    sp<InputReaderInterface> mReader;
282
283    virtual bool threadLoop();
284};
285
286
287/* Represents the state of a single input device. */
288class InputDevice {
289public:
290    InputDevice(InputReaderContext* context, int32_t id, const String8& name);
291    ~InputDevice();
292
293    inline InputReaderContext* getContext() { return mContext; }
294    inline int32_t getId() { return mId; }
295    inline const String8& getName() { return mName; }
296    inline uint32_t getSources() { return mSources; }
297
298    inline bool isExternal() { return mIsExternal; }
299    inline void setExternal(bool external) { mIsExternal = external; }
300
301    inline bool isIgnored() { return mMappers.isEmpty(); }
302
303    void dump(String8& dump);
304    void addMapper(InputMapper* mapper);
305    void configure();
306    void reset();
307    void process(const RawEvent* rawEvents, size_t count);
308    void timeoutExpired(nsecs_t when);
309
310    void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
311    int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
312    int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
313    int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
314    bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
315            const int32_t* keyCodes, uint8_t* outFlags);
316
317    int32_t getMetaState();
318
319    void fadePointer();
320
321    inline const PropertyMap& getConfiguration() {
322        return mConfiguration;
323    }
324
325private:
326    InputReaderContext* mContext;
327    int32_t mId;
328
329    Vector<InputMapper*> mMappers;
330
331    String8 mName;
332    uint32_t mSources;
333    bool mIsExternal;
334    bool mDropUntilNextSync;
335
336    typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
337    int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
338
339    PropertyMap mConfiguration;
340};
341
342
343/* An input mapper transforms raw input events into cooked event data.
344 * A single input device can have multiple associated input mappers in order to interpret
345 * different classes of events.
346 */
347class InputMapper {
348public:
349    InputMapper(InputDevice* device);
350    virtual ~InputMapper();
351
352    inline InputDevice* getDevice() { return mDevice; }
353    inline int32_t getDeviceId() { return mDevice->getId(); }
354    inline const String8 getDeviceName() { return mDevice->getName(); }
355    inline InputReaderContext* getContext() { return mContext; }
356    inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
357    inline InputDispatcherInterface* getDispatcher() { return mContext->getDispatcher(); }
358    inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
359
360    virtual uint32_t getSources() = 0;
361    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
362    virtual void dump(String8& dump);
363    virtual void configure();
364    virtual void reset();
365    virtual void process(const RawEvent* rawEvent) = 0;
366    virtual void timeoutExpired(nsecs_t when);
367
368    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
369    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
370    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
371    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
372            const int32_t* keyCodes, uint8_t* outFlags);
373
374    virtual int32_t getMetaState();
375
376    virtual void fadePointer();
377
378protected:
379    InputDevice* mDevice;
380    InputReaderContext* mContext;
381
382    static void dumpRawAbsoluteAxisInfo(String8& dump,
383            const RawAbsoluteAxisInfo& axis, const char* name);
384};
385
386
387class SwitchInputMapper : public InputMapper {
388public:
389    SwitchInputMapper(InputDevice* device);
390    virtual ~SwitchInputMapper();
391
392    virtual uint32_t getSources();
393    virtual void process(const RawEvent* rawEvent);
394
395    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
396
397private:
398    void processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue);
399};
400
401
402class KeyboardInputMapper : public InputMapper {
403public:
404    KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType);
405    virtual ~KeyboardInputMapper();
406
407    virtual uint32_t getSources();
408    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
409    virtual void dump(String8& dump);
410    virtual void configure();
411    virtual void reset();
412    virtual void process(const RawEvent* rawEvent);
413
414    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
415    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
416    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
417            const int32_t* keyCodes, uint8_t* outFlags);
418
419    virtual int32_t getMetaState();
420
421private:
422    Mutex mLock;
423
424    struct KeyDown {
425        int32_t keyCode;
426        int32_t scanCode;
427    };
428
429    uint32_t mSource;
430    int32_t mKeyboardType;
431
432    // Immutable configuration parameters.
433    struct Parameters {
434        int32_t associatedDisplayId;
435        bool orientationAware;
436    } mParameters;
437
438    struct LockedState {
439        Vector<KeyDown> keyDowns; // keys that are down
440        int32_t metaState;
441        nsecs_t downTime; // time of most recent key down
442
443        struct LedState {
444            bool avail; // led is available
445            bool on;    // we think the led is currently on
446        };
447        LedState capsLockLedState;
448        LedState numLockLedState;
449        LedState scrollLockLedState;
450    } mLocked;
451
452    void initializeLocked();
453
454    void configureParameters();
455    void dumpParameters(String8& dump);
456
457    bool isKeyboardOrGamepadKey(int32_t scanCode);
458
459    void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
460            uint32_t policyFlags);
461
462    ssize_t findKeyDownLocked(int32_t scanCode);
463
464    void resetLedStateLocked();
465    void initializeLedStateLocked(LockedState::LedState& ledState, int32_t led);
466    void updateLedStateLocked(bool reset);
467    void updateLedStateForModifierLocked(LockedState::LedState& ledState, int32_t led,
468            int32_t modifier, bool reset);
469};
470
471
472class CursorInputMapper : public InputMapper {
473public:
474    CursorInputMapper(InputDevice* device);
475    virtual ~CursorInputMapper();
476
477    virtual uint32_t getSources();
478    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
479    virtual void dump(String8& dump);
480    virtual void configure();
481    virtual void reset();
482    virtual void process(const RawEvent* rawEvent);
483
484    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
485
486    virtual void fadePointer();
487
488private:
489    // Amount that trackball needs to move in order to generate a key event.
490    static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
491
492    Mutex mLock;
493
494    // Immutable configuration parameters.
495    struct Parameters {
496        enum Mode {
497            MODE_POINTER,
498            MODE_NAVIGATION,
499        };
500
501        Mode mode;
502        int32_t associatedDisplayId;
503        bool orientationAware;
504    } mParameters;
505
506    struct Accumulator {
507        enum {
508            FIELD_BUTTONS = 1,
509            FIELD_REL_X = 2,
510            FIELD_REL_Y = 4,
511            FIELD_REL_WHEEL = 8,
512            FIELD_REL_HWHEEL = 16,
513        };
514
515        uint32_t fields;
516
517        uint32_t buttonDown;
518        uint32_t buttonUp;
519
520        int32_t relX;
521        int32_t relY;
522        int32_t relWheel;
523        int32_t relHWheel;
524
525        inline void clear() {
526            fields = 0;
527        }
528    } mAccumulator;
529
530    int32_t mSource;
531    float mXScale;
532    float mYScale;
533    float mXPrecision;
534    float mYPrecision;
535
536    bool mHaveVWheel;
537    bool mHaveHWheel;
538    float mVWheelScale;
539    float mHWheelScale;
540
541    sp<PointerControllerInterface> mPointerController;
542
543    struct LockedState {
544        int32_t buttonState;
545        nsecs_t downTime;
546    } mLocked;
547
548    void initializeLocked();
549
550    void configureParameters();
551    void dumpParameters(String8& dump);
552
553    void sync(nsecs_t when);
554};
555
556
557class TouchInputMapper : public InputMapper {
558public:
559    TouchInputMapper(InputDevice* device);
560    virtual ~TouchInputMapper();
561
562    virtual uint32_t getSources();
563    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
564    virtual void dump(String8& dump);
565    virtual void configure();
566    virtual void reset();
567
568    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
569    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
570    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
571            const int32_t* keyCodes, uint8_t* outFlags);
572
573    virtual void fadePointer();
574    virtual void timeoutExpired(nsecs_t when);
575
576protected:
577    Mutex mLock;
578
579    struct VirtualKey {
580        int32_t keyCode;
581        int32_t scanCode;
582        uint32_t flags;
583
584        // computed hit box, specified in touch screen coords based on known display size
585        int32_t hitLeft;
586        int32_t hitTop;
587        int32_t hitRight;
588        int32_t hitBottom;
589
590        inline bool isHit(int32_t x, int32_t y) const {
591            return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
592        }
593    };
594
595    // Raw data for a single pointer.
596    struct PointerData {
597        uint32_t id;
598        int32_t x;
599        int32_t y;
600        int32_t pressure;
601        int32_t touchMajor;
602        int32_t touchMinor;
603        int32_t toolMajor;
604        int32_t toolMinor;
605        int32_t orientation;
606        int32_t distance;
607        bool isStylus;
608
609        inline bool operator== (const PointerData& other) const {
610            return id == other.id
611                    && x == other.x
612                    && y == other.y
613                    && pressure == other.pressure
614                    && touchMajor == other.touchMajor
615                    && touchMinor == other.touchMinor
616                    && toolMajor == other.toolMajor
617                    && toolMinor == other.toolMinor
618                    && orientation == other.orientation
619                    && distance == other.distance;
620        }
621        inline bool operator!= (const PointerData& other) const {
622            return !(*this == other);
623        }
624    };
625
626    // Raw data for a collection of pointers including a pointer id mapping table.
627    struct TouchData {
628        uint32_t pointerCount;
629        PointerData pointers[MAX_POINTERS];
630        BitSet32 idBits;
631        uint32_t idToIndex[MAX_POINTER_ID + 1];
632        int32_t buttonState;
633
634        void copyFrom(const TouchData& other) {
635            pointerCount = other.pointerCount;
636            idBits = other.idBits;
637            buttonState = other.buttonState;
638
639            for (uint32_t i = 0; i < pointerCount; i++) {
640                pointers[i] = other.pointers[i];
641
642                int id = pointers[i].id;
643                idToIndex[id] = other.idToIndex[id];
644            }
645        }
646
647        inline void clear() {
648            pointerCount = 0;
649            idBits.clear();
650            buttonState = 0;
651        }
652
653        void getCentroid(float* outX, float* outY) {
654            float x = 0, y = 0;
655            if (pointerCount != 0) {
656                for (uint32_t i = 0; i < pointerCount; i++) {
657                    x += pointers[i].x;
658                    y += pointers[i].y;
659                }
660                x /= pointerCount;
661                y /= pointerCount;
662            }
663            *outX = x;
664            *outY = y;
665        }
666    };
667
668    // Input sources supported by the device.
669    uint32_t mTouchSource; // sources when reporting touch data
670    uint32_t mPointerSource; // sources when reporting pointer gestures
671
672    // Immutable configuration parameters.
673    struct Parameters {
674        enum DeviceType {
675            DEVICE_TYPE_TOUCH_SCREEN,
676            DEVICE_TYPE_TOUCH_PAD,
677            DEVICE_TYPE_POINTER,
678        };
679
680        DeviceType deviceType;
681        int32_t associatedDisplayId;
682        bool orientationAware;
683
684        bool useBadTouchFilter;
685        bool useJumpyTouchFilter;
686        bool useAveragingTouchFilter;
687        nsecs_t virtualKeyQuietTime;
688
689        enum GestureMode {
690            GESTURE_MODE_POINTER,
691            GESTURE_MODE_SPOTS,
692        };
693        GestureMode gestureMode;
694    } mParameters;
695
696    // Immutable calibration parameters in parsed form.
697    struct Calibration {
698        // Touch Size
699        enum TouchSizeCalibration {
700            TOUCH_SIZE_CALIBRATION_DEFAULT,
701            TOUCH_SIZE_CALIBRATION_NONE,
702            TOUCH_SIZE_CALIBRATION_GEOMETRIC,
703            TOUCH_SIZE_CALIBRATION_PRESSURE,
704        };
705
706        TouchSizeCalibration touchSizeCalibration;
707
708        // Tool Size
709        enum ToolSizeCalibration {
710            TOOL_SIZE_CALIBRATION_DEFAULT,
711            TOOL_SIZE_CALIBRATION_NONE,
712            TOOL_SIZE_CALIBRATION_GEOMETRIC,
713            TOOL_SIZE_CALIBRATION_LINEAR,
714            TOOL_SIZE_CALIBRATION_AREA,
715        };
716
717        ToolSizeCalibration toolSizeCalibration;
718        bool haveToolSizeLinearScale;
719        float toolSizeLinearScale;
720        bool haveToolSizeLinearBias;
721        float toolSizeLinearBias;
722        bool haveToolSizeAreaScale;
723        float toolSizeAreaScale;
724        bool haveToolSizeAreaBias;
725        float toolSizeAreaBias;
726        bool haveToolSizeIsSummed;
727        bool toolSizeIsSummed;
728
729        // Pressure
730        enum PressureCalibration {
731            PRESSURE_CALIBRATION_DEFAULT,
732            PRESSURE_CALIBRATION_NONE,
733            PRESSURE_CALIBRATION_PHYSICAL,
734            PRESSURE_CALIBRATION_AMPLITUDE,
735        };
736        enum PressureSource {
737            PRESSURE_SOURCE_DEFAULT,
738            PRESSURE_SOURCE_PRESSURE,
739            PRESSURE_SOURCE_TOUCH,
740        };
741
742        PressureCalibration pressureCalibration;
743        PressureSource pressureSource;
744        bool havePressureScale;
745        float pressureScale;
746
747        // Size
748        enum SizeCalibration {
749            SIZE_CALIBRATION_DEFAULT,
750            SIZE_CALIBRATION_NONE,
751            SIZE_CALIBRATION_NORMALIZED,
752        };
753
754        SizeCalibration sizeCalibration;
755
756        // Orientation
757        enum OrientationCalibration {
758            ORIENTATION_CALIBRATION_DEFAULT,
759            ORIENTATION_CALIBRATION_NONE,
760            ORIENTATION_CALIBRATION_INTERPOLATED,
761            ORIENTATION_CALIBRATION_VECTOR,
762        };
763
764        OrientationCalibration orientationCalibration;
765
766        // Distance
767        enum DistanceCalibration {
768            DISTANCE_CALIBRATION_DEFAULT,
769            DISTANCE_CALIBRATION_NONE,
770            DISTANCE_CALIBRATION_SCALED,
771        };
772
773        DistanceCalibration distanceCalibration;
774        bool haveDistanceScale;
775        float distanceScale;
776    } mCalibration;
777
778    // Raw axis information from the driver.
779    struct RawAxes {
780        RawAbsoluteAxisInfo x;
781        RawAbsoluteAxisInfo y;
782        RawAbsoluteAxisInfo pressure;
783        RawAbsoluteAxisInfo touchMajor;
784        RawAbsoluteAxisInfo touchMinor;
785        RawAbsoluteAxisInfo toolMajor;
786        RawAbsoluteAxisInfo toolMinor;
787        RawAbsoluteAxisInfo orientation;
788        RawAbsoluteAxisInfo distance;
789        RawAbsoluteAxisInfo trackingId;
790        RawAbsoluteAxisInfo slot;
791    } mRawAxes;
792
793    // Current and previous touch sample data.
794    TouchData mCurrentTouch;
795    PointerProperties mCurrentTouchProperties[MAX_POINTERS];
796    PointerCoords mCurrentTouchCoords[MAX_POINTERS];
797
798    TouchData mLastTouch;
799    PointerProperties mLastTouchProperties[MAX_POINTERS];
800    PointerCoords mLastTouchCoords[MAX_POINTERS];
801
802    // The time the primary pointer last went down.
803    nsecs_t mDownTime;
804
805    // The pointer controller, or null if the device is not a pointer.
806    sp<PointerControllerInterface> mPointerController;
807
808    struct LockedState {
809        Vector<VirtualKey> virtualKeys;
810
811        // The surface orientation and width and height set by configureSurfaceLocked().
812        int32_t surfaceOrientation;
813        int32_t surfaceWidth, surfaceHeight;
814
815        // The associated display orientation and width and height set by configureSurfaceLocked().
816        int32_t associatedDisplayOrientation;
817        int32_t associatedDisplayWidth, associatedDisplayHeight;
818
819        // Translation and scaling factors, orientation-independent.
820        float xScale;
821        float xPrecision;
822
823        float yScale;
824        float yPrecision;
825
826        float geometricScale;
827
828        float toolSizeLinearScale;
829        float toolSizeLinearBias;
830        float toolSizeAreaScale;
831        float toolSizeAreaBias;
832
833        float pressureScale;
834
835        float sizeScale;
836
837        float orientationScale;
838
839        float distanceScale;
840
841        // Oriented motion ranges for input device info.
842        struct OrientedRanges {
843            InputDeviceInfo::MotionRange x;
844            InputDeviceInfo::MotionRange y;
845
846            bool havePressure;
847            InputDeviceInfo::MotionRange pressure;
848
849            bool haveSize;
850            InputDeviceInfo::MotionRange size;
851
852            bool haveTouchSize;
853            InputDeviceInfo::MotionRange touchMajor;
854            InputDeviceInfo::MotionRange touchMinor;
855
856            bool haveToolSize;
857            InputDeviceInfo::MotionRange toolMajor;
858            InputDeviceInfo::MotionRange toolMinor;
859
860            bool haveOrientation;
861            InputDeviceInfo::MotionRange orientation;
862
863            bool haveDistance;
864            InputDeviceInfo::MotionRange distance;
865        } orientedRanges;
866
867        // Oriented dimensions and precision.
868        float orientedSurfaceWidth, orientedSurfaceHeight;
869        float orientedXPrecision, orientedYPrecision;
870
871        struct CurrentVirtualKeyState {
872            bool down;
873            nsecs_t downTime;
874            int32_t keyCode;
875            int32_t scanCode;
876        } currentVirtualKey;
877
878        // Scale factor for gesture based pointer movements.
879        float pointerGestureXMovementScale;
880        float pointerGestureYMovementScale;
881
882        // Scale factor for gesture based zooming and other freeform motions.
883        float pointerGestureXZoomScale;
884        float pointerGestureYZoomScale;
885
886        // The maximum swipe width.
887        float pointerGestureMaxSwipeWidth;
888    } mLocked;
889
890    virtual void configureParameters();
891    virtual void dumpParameters(String8& dump);
892    virtual void configureRawAxes();
893    virtual void dumpRawAxes(String8& dump);
894    virtual bool configureSurfaceLocked();
895    virtual void dumpSurfaceLocked(String8& dump);
896    virtual void configureVirtualKeysLocked();
897    virtual void dumpVirtualKeysLocked(String8& dump);
898    virtual void parseCalibration();
899    virtual void resolveCalibration();
900    virtual void dumpCalibration(String8& dump);
901
902    enum TouchResult {
903        // Dispatch the touch normally.
904        DISPATCH_TOUCH,
905        // Do not dispatch the touch, but keep tracking the current stroke.
906        SKIP_TOUCH,
907        // Do not dispatch the touch, and drop all information associated with the current stoke
908        // so the next movement will appear as a new down.
909        DROP_STROKE
910    };
911
912    void syncTouch(nsecs_t when, bool havePointerIds);
913
914private:
915    /* Maximum number of historical samples to average. */
916    static const uint32_t AVERAGING_HISTORY_SIZE = 5;
917
918    /* Slop distance for jumpy pointer detection.
919     * The vertical range of the screen divided by this is our epsilon value. */
920    static const uint32_t JUMPY_EPSILON_DIVISOR = 212;
921
922    /* Number of jumpy points to drop for touchscreens that need it. */
923    static const uint32_t JUMPY_TRANSITION_DROPS = 3;
924    static const uint32_t JUMPY_DROP_LIMIT = 3;
925
926    /* Maximum squared distance for averaging.
927     * If moving farther than this, turn of averaging to avoid lag in response. */
928    static const uint64_t AVERAGING_DISTANCE_LIMIT = 75 * 75;
929
930    struct AveragingTouchFilterState {
931        // Individual history tracks are stored by pointer id
932        uint32_t historyStart[MAX_POINTERS];
933        uint32_t historyEnd[MAX_POINTERS];
934        struct {
935            struct {
936                int32_t x;
937                int32_t y;
938                int32_t pressure;
939            } pointers[MAX_POINTERS];
940        } historyData[AVERAGING_HISTORY_SIZE];
941    } mAveragingTouchFilter;
942
943    struct JumpyTouchFilterState {
944        uint32_t jumpyPointsDropped;
945    } mJumpyTouchFilter;
946
947    struct PointerDistanceHeapElement {
948        uint32_t currentPointerIndex : 8;
949        uint32_t lastPointerIndex : 8;
950        uint64_t distance : 48; // squared distance
951    };
952
953    struct PointerGesture {
954        enum Mode {
955            // No fingers, button is not pressed.
956            // Nothing happening.
957            NEUTRAL,
958
959            // No fingers, button is not pressed.
960            // Tap detected.
961            // Emits DOWN and UP events at the pointer location.
962            TAP,
963
964            // Exactly one finger dragging following a tap.
965            // Pointer follows the active finger.
966            // Emits DOWN, MOVE and UP events at the pointer location.
967            TAP_DRAG,
968
969            // Button is pressed.
970            // Pointer follows the active finger if there is one.  Other fingers are ignored.
971            // Emits DOWN, MOVE and UP events at the pointer location.
972            BUTTON_CLICK_OR_DRAG,
973
974            // Exactly one finger, button is not pressed.
975            // Pointer follows the active finger.
976            // Emits HOVER_MOVE events at the pointer location.
977            HOVER,
978
979            // Exactly two fingers but neither have moved enough to clearly indicate
980            // whether a swipe or freeform gesture was intended.  We consider the
981            // pointer to be pressed so this enables clicking or long-pressing on buttons.
982            // Pointer does not move.
983            // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
984            PRESS,
985
986            // Exactly two fingers moving in the same direction, button is not pressed.
987            // Pointer does not move.
988            // Emits DOWN, MOVE and UP events with a single pointer coordinate that
989            // follows the midpoint between both fingers.
990            SWIPE,
991
992            // Two or more fingers moving in arbitrary directions, button is not pressed.
993            // Pointer does not move.
994            // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
995            // each finger individually relative to the initial centroid of the finger.
996            FREEFORM,
997
998            // Waiting for quiet time to end before starting the next gesture.
999            QUIET,
1000        };
1001
1002        // Time the first finger went down.
1003        nsecs_t firstTouchTime;
1004
1005        // The active pointer id from the raw touch data.
1006        int32_t activeTouchId; // -1 if none
1007
1008        // The active pointer id from the gesture last delivered to the application.
1009        int32_t activeGestureId; // -1 if none
1010
1011        // Pointer coords and ids for the current and previous pointer gesture.
1012        Mode currentGestureMode;
1013        BitSet32 currentGestureIdBits;
1014        uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
1015        PointerProperties currentGestureProperties[MAX_POINTERS];
1016        PointerCoords currentGestureCoords[MAX_POINTERS];
1017
1018        Mode lastGestureMode;
1019        BitSet32 lastGestureIdBits;
1020        uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
1021        PointerProperties lastGestureProperties[MAX_POINTERS];
1022        PointerCoords lastGestureCoords[MAX_POINTERS];
1023
1024        // Pointer coords and ids for the current spots.
1025        PointerControllerInterface::SpotGesture spotGesture;
1026        BitSet32 spotIdBits; // same set of ids as touch ids
1027        uint32_t spotIdToIndex[MAX_POINTER_ID + 1];
1028        PointerCoords spotCoords[MAX_POINTERS];
1029
1030        // Time the pointer gesture last went down.
1031        nsecs_t downTime;
1032
1033        // Time when the pointer went down for a TAP.
1034        nsecs_t tapDownTime;
1035
1036        // Time when the pointer went up for a TAP.
1037        nsecs_t tapUpTime;
1038
1039        // Location of initial tap.
1040        float tapX, tapY;
1041
1042        // Time we started waiting for quiescence.
1043        nsecs_t quietTime;
1044
1045        // Reference points for multitouch gestures.
1046        float referenceTouchX;    // reference touch X/Y coordinates in surface units
1047        float referenceTouchY;
1048        float referenceGestureX;  // reference gesture X/Y coordinates in pixels
1049        float referenceGestureY;
1050
1051        // Describes how touch ids are mapped to gesture ids for freeform gestures.
1052        uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
1053
1054        // A velocity tracker for determining whether to switch active pointers during drags.
1055        VelocityTracker velocityTracker;
1056
1057        void reset() {
1058            firstTouchTime = LLONG_MIN;
1059            activeTouchId = -1;
1060            activeGestureId = -1;
1061            currentGestureMode = NEUTRAL;
1062            currentGestureIdBits.clear();
1063            lastGestureMode = NEUTRAL;
1064            lastGestureIdBits.clear();
1065            spotGesture = PointerControllerInterface::SPOT_GESTURE_NEUTRAL;
1066            spotIdBits.clear();
1067            downTime = 0;
1068            velocityTracker.clear();
1069            resetTap();
1070            resetQuietTime();
1071        }
1072
1073        void resetTap() {
1074            tapDownTime = LLONG_MIN;
1075            tapUpTime = LLONG_MIN;
1076        }
1077
1078        void resetQuietTime() {
1079            quietTime = LLONG_MIN;
1080        }
1081    } mPointerGesture;
1082
1083    void initializeLocked();
1084
1085    TouchResult consumeOffScreenTouches(nsecs_t when, uint32_t policyFlags);
1086    void dispatchTouches(nsecs_t when, uint32_t policyFlags);
1087    void prepareTouches(int32_t* outEdgeFlags, float* outXPrecision, float* outYPrecision);
1088    void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
1089    bool preparePointerGestures(nsecs_t when,
1090            bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout);
1091    void moveSpotsLocked();
1092
1093    // Dispatches a motion event.
1094    // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
1095    // method will take care of setting the index and transmuting the action to DOWN or UP
1096    // it is the first / last pointer to go down / up.
1097    void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
1098            int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
1099            int32_t edgeFlags,
1100            const PointerProperties* properties, const PointerCoords* coords,
1101            const uint32_t* idToIndex, BitSet32 idBits,
1102            int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
1103
1104    // Updates pointer coords and properties for pointers with specified ids that have moved.
1105    // Returns true if any of them changed.
1106    bool updateMovedPointers(const PointerProperties* inProperties,
1107            const PointerCoords* inCoords, const uint32_t* inIdToIndex,
1108            PointerProperties* outProperties, PointerCoords* outCoords,
1109            const uint32_t* outIdToIndex, BitSet32 idBits) const;
1110
1111    void suppressSwipeOntoVirtualKeys(nsecs_t when);
1112
1113    int32_t getTouchToolType(bool isStylus) const;
1114    bool isPointInsideSurfaceLocked(int32_t x, int32_t y);
1115    const VirtualKey* findVirtualKeyHitLocked(int32_t x, int32_t y);
1116
1117    bool applyBadTouchFilter();
1118    bool applyJumpyTouchFilter();
1119    void applyAveragingTouchFilter();
1120    void calculatePointerIds();
1121};
1122
1123
1124class SingleTouchInputMapper : public TouchInputMapper {
1125public:
1126    SingleTouchInputMapper(InputDevice* device);
1127    virtual ~SingleTouchInputMapper();
1128
1129    virtual void reset();
1130    virtual void process(const RawEvent* rawEvent);
1131
1132protected:
1133    virtual void configureRawAxes();
1134
1135private:
1136    struct Accumulator {
1137        enum {
1138            FIELD_BTN_TOUCH = 1,
1139            FIELD_ABS_X = 2,
1140            FIELD_ABS_Y = 4,
1141            FIELD_ABS_PRESSURE = 8,
1142            FIELD_ABS_TOOL_WIDTH = 16,
1143            FIELD_BUTTONS = 32,
1144        };
1145
1146        uint32_t fields;
1147
1148        bool btnTouch;
1149        int32_t absX;
1150        int32_t absY;
1151        int32_t absPressure;
1152        int32_t absToolWidth;
1153
1154        uint32_t buttonDown;
1155        uint32_t buttonUp;
1156
1157        inline void clear() {
1158            fields = 0;
1159            buttonDown = 0;
1160            buttonUp = 0;
1161        }
1162    } mAccumulator;
1163
1164    bool mDown;
1165    int32_t mX;
1166    int32_t mY;
1167    int32_t mPressure;
1168    int32_t mToolWidth;
1169    int32_t mButtonState;
1170
1171    void clearState();
1172
1173    void sync(nsecs_t when);
1174};
1175
1176
1177class MultiTouchInputMapper : public TouchInputMapper {
1178public:
1179    MultiTouchInputMapper(InputDevice* device);
1180    virtual ~MultiTouchInputMapper();
1181
1182    virtual void reset();
1183    virtual void process(const RawEvent* rawEvent);
1184
1185protected:
1186    virtual void configureRawAxes();
1187
1188private:
1189    struct Accumulator {
1190        enum {
1191            FIELD_ABS_MT_POSITION_X = 1 << 0,
1192            FIELD_ABS_MT_POSITION_Y = 1 << 1,
1193            FIELD_ABS_MT_TOUCH_MAJOR = 1 << 2,
1194            FIELD_ABS_MT_TOUCH_MINOR = 1 << 3,
1195            FIELD_ABS_MT_WIDTH_MAJOR = 1 << 4,
1196            FIELD_ABS_MT_WIDTH_MINOR = 1 << 5,
1197            FIELD_ABS_MT_ORIENTATION = 1 << 6,
1198            FIELD_ABS_MT_TRACKING_ID = 1 << 7,
1199            FIELD_ABS_MT_PRESSURE = 1 << 8,
1200            FIELD_ABS_MT_TOOL_TYPE = 1 << 9,
1201            FIELD_ABS_MT_DISTANCE = 1 << 10,
1202        };
1203
1204        struct Slot {
1205            uint32_t fields; // 0 if slot is unused
1206
1207            int32_t absMTPositionX;
1208            int32_t absMTPositionY;
1209            int32_t absMTTouchMajor;
1210            int32_t absMTTouchMinor;
1211            int32_t absMTWidthMajor;
1212            int32_t absMTWidthMinor;
1213            int32_t absMTOrientation;
1214            int32_t absMTTrackingId;
1215            int32_t absMTPressure;
1216            int32_t absMTToolType;
1217            int32_t absMTDistance;
1218
1219            inline Slot() {
1220                clear();
1221            }
1222
1223            inline void clear() {
1224                fields = 0;
1225            }
1226        };
1227
1228        // Current slot index.
1229        int32_t currentSlot;
1230
1231        // Array of slots.
1232        Slot* slots;
1233
1234        // Bitfield of buttons that went down or up.
1235        uint32_t buttonDown;
1236        uint32_t buttonUp;
1237
1238        Accumulator() : slots(NULL) {
1239            clear(false);
1240        }
1241
1242        ~Accumulator() {
1243            delete[] slots;
1244        }
1245
1246        void allocateSlots(size_t slotCount) {
1247            slots = new Slot[slotCount];
1248        }
1249
1250        void clear(size_t slotCount) {
1251            for (size_t i = 0; i < slotCount; i++) {
1252                slots[i].clear();
1253            }
1254            currentSlot = 0;
1255            buttonDown = 0;
1256            buttonUp = 0;
1257        }
1258    } mAccumulator;
1259
1260    size_t mSlotCount;
1261    bool mUsingSlotsProtocol;
1262
1263    int32_t mButtonState;
1264
1265    void clearState();
1266
1267    void sync(nsecs_t when);
1268};
1269
1270
1271class JoystickInputMapper : public InputMapper {
1272public:
1273    JoystickInputMapper(InputDevice* device);
1274    virtual ~JoystickInputMapper();
1275
1276    virtual uint32_t getSources();
1277    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1278    virtual void dump(String8& dump);
1279    virtual void configure();
1280    virtual void reset();
1281    virtual void process(const RawEvent* rawEvent);
1282
1283private:
1284    struct Axis {
1285        RawAbsoluteAxisInfo rawAxisInfo;
1286        AxisInfo axisInfo;
1287
1288        bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1289
1290        float scale;   // scale factor from raw to normalized values
1291        float offset;  // offset to add after scaling for normalization
1292        float highScale;  // scale factor from raw to normalized values of high split
1293        float highOffset; // offset to add after scaling for normalization of high split
1294
1295        float min;     // normalized inclusive minimum
1296        float max;     // normalized inclusive maximum
1297        float flat;    // normalized flat region size
1298        float fuzz;    // normalized error tolerance
1299
1300        float filter;  // filter out small variations of this size
1301        float currentValue; // current value
1302        float newValue; // most recent value
1303        float highCurrentValue; // current value of high split
1304        float highNewValue; // most recent value of high split
1305
1306        void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
1307                bool explicitlyMapped, float scale, float offset,
1308                float highScale, float highOffset,
1309                float min, float max, float flat, float fuzz) {
1310            this->rawAxisInfo = rawAxisInfo;
1311            this->axisInfo = axisInfo;
1312            this->explicitlyMapped = explicitlyMapped;
1313            this->scale = scale;
1314            this->offset = offset;
1315            this->highScale = highScale;
1316            this->highOffset = highOffset;
1317            this->min = min;
1318            this->max = max;
1319            this->flat = flat;
1320            this->fuzz = fuzz;
1321            this->filter = 0;
1322            resetValue();
1323        }
1324
1325        void resetValue() {
1326            this->currentValue = 0;
1327            this->newValue = 0;
1328            this->highCurrentValue = 0;
1329            this->highNewValue = 0;
1330        }
1331    };
1332
1333    // Axes indexed by raw ABS_* axis index.
1334    KeyedVector<int32_t, Axis> mAxes;
1335
1336    void sync(nsecs_t when, bool force);
1337
1338    bool haveAxis(int32_t axisId);
1339    void pruneAxes(bool ignoreExplicitlyMappedAxes);
1340    bool filterAxes(bool force);
1341
1342    static bool hasValueChangedSignificantly(float filter,
1343            float newValue, float currentValue, float min, float max);
1344    static bool hasMovedNearerToValueWithinFilteredRange(float filter,
1345            float newValue, float currentValue, float thresholdValue);
1346
1347    static bool isCenteredAxis(int32_t axis);
1348};
1349
1350} // namespace android
1351
1352#endif // _UI_INPUT_READER_H
1353