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