InputReader.h revision 05dc66ada6b61a6bdf806ffaa62617ac5394695d
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 InputReaderPolicyInterface* getPolicy() = 0;
163    virtual InputDispatcherInterface* getDispatcher() = 0;
164    virtual EventHubInterface* getEventHub() = 0;
165};
166
167
168/* The input reader reads raw event data from the event hub and processes it into input events
169 * that it sends to the input dispatcher.  Some functions of the input reader, such as early
170 * event filtering in low power states, are controlled by a separate policy object.
171 *
172 * IMPORTANT INVARIANT:
173 *     Because the policy and dispatcher can potentially block or cause re-entrance into
174 *     the input reader, the input reader never calls into other components while holding
175 *     an exclusive internal lock whenever re-entrance can happen.
176 */
177class InputReader : public InputReaderInterface, protected InputReaderContext {
178public:
179    InputReader(const sp<EventHubInterface>& eventHub,
180            const sp<InputReaderPolicyInterface>& policy,
181            const sp<InputDispatcherInterface>& dispatcher);
182    virtual ~InputReader();
183
184    virtual void dump(String8& dump);
185
186    virtual void loopOnce();
187
188    virtual void getInputConfiguration(InputConfiguration* outConfiguration);
189
190    virtual status_t getInputDeviceInfo(int32_t deviceId, InputDeviceInfo* outDeviceInfo);
191    virtual void getInputDeviceIds(Vector<int32_t>& outDeviceIds);
192
193    virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
194            int32_t scanCode);
195    virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
196            int32_t keyCode);
197    virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
198            int32_t sw);
199
200    virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
201            size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags);
202
203protected:
204    // These methods are protected virtual so they can be overridden and instrumented
205    // by test cases.
206    virtual InputDevice* createDevice(int32_t deviceId, const String8& name, uint32_t classes);
207
208private:
209    sp<EventHubInterface> mEventHub;
210    sp<InputReaderPolicyInterface> mPolicy;
211    sp<InputDispatcherInterface> mDispatcher;
212
213    virtual InputReaderPolicyInterface* getPolicy() { return mPolicy.get(); }
214    virtual InputDispatcherInterface* getDispatcher() { return mDispatcher.get(); }
215    virtual EventHubInterface* getEventHub() { return mEventHub.get(); }
216
217    // This reader/writer lock guards the list of input devices.
218    // The writer lock must be held whenever the list of input devices is modified
219    //   and then promptly released.
220    // The reader lock must be held whenever the list of input devices is traversed or an
221    //   input device in the list is accessed.
222    // This lock only protects the registry and prevents inadvertent deletion of device objects
223    // that are in use.  Individual devices are responsible for guarding their own internal state
224    // as needed for concurrent operation.
225    RWLock mDeviceRegistryLock;
226    KeyedVector<int32_t, InputDevice*> mDevices;
227
228    // low-level input event decoding and device management
229    void process(const RawEvent* rawEvent);
230
231    void addDevice(int32_t deviceId);
232    void removeDevice(int32_t deviceId);
233    void configureExcludedDevices();
234
235    void consumeEvent(const RawEvent* rawEvent);
236
237    void handleConfigurationChanged(nsecs_t when);
238
239    // state management for all devices
240    Mutex mStateLock;
241
242    int32_t mGlobalMetaState;
243    virtual void updateGlobalMetaState();
244    virtual int32_t getGlobalMetaState();
245
246    virtual void fadePointer();
247
248    InputConfiguration mInputConfiguration;
249    void updateInputConfiguration();
250
251    nsecs_t mDisableVirtualKeysTimeout;
252    virtual void disableVirtualKeysUntil(nsecs_t time);
253    virtual bool shouldDropVirtualKey(nsecs_t now,
254            InputDevice* device, int32_t keyCode, int32_t scanCode);
255
256    // state queries
257    typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
258    int32_t getState(int32_t deviceId, uint32_t sourceMask, int32_t code,
259            GetStateFunc getStateFunc);
260    bool markSupportedKeyCodes(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
261            const int32_t* keyCodes, uint8_t* outFlags);
262};
263
264
265/* Reads raw events from the event hub and processes them, endlessly. */
266class InputReaderThread : public Thread {
267public:
268    InputReaderThread(const sp<InputReaderInterface>& reader);
269    virtual ~InputReaderThread();
270
271private:
272    sp<InputReaderInterface> mReader;
273
274    virtual bool threadLoop();
275};
276
277
278/* Represents the state of a single input device. */
279class InputDevice {
280public:
281    InputDevice(InputReaderContext* context, int32_t id, const String8& name);
282    ~InputDevice();
283
284    inline InputReaderContext* getContext() { return mContext; }
285    inline int32_t getId() { return mId; }
286    inline const String8& getName() { return mName; }
287    inline uint32_t getSources() { return mSources; }
288
289    inline bool isIgnored() { return mMappers.isEmpty(); }
290
291    void dump(String8& dump);
292    void addMapper(InputMapper* mapper);
293    void configure();
294    void reset();
295    void process(const RawEvent* rawEvent);
296
297    void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
298    int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
299    int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
300    int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
301    bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
302            const int32_t* keyCodes, uint8_t* outFlags);
303
304    int32_t getMetaState();
305
306    void fadePointer();
307
308    inline const PropertyMap& getConfiguration() {
309        return mConfiguration;
310    }
311
312private:
313    InputReaderContext* mContext;
314    int32_t mId;
315
316    Vector<InputMapper*> mMappers;
317
318    String8 mName;
319    uint32_t mSources;
320
321    typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
322    int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
323
324    PropertyMap mConfiguration;
325};
326
327
328/* An input mapper transforms raw input events into cooked event data.
329 * A single input device can have multiple associated input mappers in order to interpret
330 * different classes of events.
331 */
332class InputMapper {
333public:
334    InputMapper(InputDevice* device);
335    virtual ~InputMapper();
336
337    inline InputDevice* getDevice() { return mDevice; }
338    inline int32_t getDeviceId() { return mDevice->getId(); }
339    inline const String8 getDeviceName() { return mDevice->getName(); }
340    inline InputReaderContext* getContext() { return mContext; }
341    inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
342    inline InputDispatcherInterface* getDispatcher() { return mContext->getDispatcher(); }
343    inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
344
345    virtual uint32_t getSources() = 0;
346    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
347    virtual void dump(String8& dump);
348    virtual void configure();
349    virtual void reset();
350    virtual void process(const RawEvent* rawEvent) = 0;
351
352    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
353    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
354    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
355    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
356            const int32_t* keyCodes, uint8_t* outFlags);
357
358    virtual int32_t getMetaState();
359
360    virtual void fadePointer();
361
362protected:
363    InputDevice* mDevice;
364    InputReaderContext* mContext;
365
366    static void dumpRawAbsoluteAxisInfo(String8& dump,
367            const RawAbsoluteAxisInfo& axis, const char* name);
368};
369
370
371class SwitchInputMapper : public InputMapper {
372public:
373    SwitchInputMapper(InputDevice* device);
374    virtual ~SwitchInputMapper();
375
376    virtual uint32_t getSources();
377    virtual void process(const RawEvent* rawEvent);
378
379    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
380
381private:
382    void processSwitch(nsecs_t when, int32_t switchCode, int32_t switchValue);
383};
384
385
386class KeyboardInputMapper : public InputMapper {
387public:
388    KeyboardInputMapper(InputDevice* device, uint32_t sources, int32_t keyboardType);
389    virtual ~KeyboardInputMapper();
390
391    virtual uint32_t getSources();
392    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
393    virtual void dump(String8& dump);
394    virtual void configure();
395    virtual void reset();
396    virtual void process(const RawEvent* rawEvent);
397
398    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
399    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
400    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
401            const int32_t* keyCodes, uint8_t* outFlags);
402
403    virtual int32_t getMetaState();
404
405private:
406    Mutex mLock;
407
408    struct KeyDown {
409        int32_t keyCode;
410        int32_t scanCode;
411    };
412
413    uint32_t mSources;
414    int32_t mKeyboardType;
415
416    // Immutable configuration parameters.
417    struct Parameters {
418        int32_t associatedDisplayId;
419        bool orientationAware;
420    } mParameters;
421
422    struct LockedState {
423        Vector<KeyDown> keyDowns; // keys that are down
424        int32_t metaState;
425        nsecs_t downTime; // time of most recent key down
426
427        struct LedState {
428            bool avail; // led is available
429            bool on;    // we think the led is currently on
430        };
431        LedState capsLockLedState;
432        LedState numLockLedState;
433        LedState scrollLockLedState;
434    } mLocked;
435
436    void initializeLocked();
437
438    void configureParameters();
439    void dumpParameters(String8& dump);
440
441    bool isKeyboardOrGamepadKey(int32_t scanCode);
442
443    void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
444            uint32_t policyFlags);
445
446    ssize_t findKeyDownLocked(int32_t scanCode);
447
448    void resetLedStateLocked();
449    void initializeLedStateLocked(LockedState::LedState& ledState, int32_t led);
450    void updateLedStateLocked(bool reset);
451    void updateLedStateForModifierLocked(LockedState::LedState& ledState, int32_t led,
452            int32_t modifier, bool reset);
453};
454
455
456class CursorInputMapper : public InputMapper {
457public:
458    CursorInputMapper(InputDevice* device);
459    virtual ~CursorInputMapper();
460
461    virtual uint32_t getSources();
462    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
463    virtual void dump(String8& dump);
464    virtual void configure();
465    virtual void reset();
466    virtual void process(const RawEvent* rawEvent);
467
468    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
469
470    virtual void fadePointer();
471
472private:
473    // Amount that trackball needs to move in order to generate a key event.
474    static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
475
476    Mutex mLock;
477
478    // Immutable configuration parameters.
479    struct Parameters {
480        enum Mode {
481            MODE_POINTER,
482            MODE_NAVIGATION,
483        };
484
485        Mode mode;
486        int32_t associatedDisplayId;
487        bool orientationAware;
488    } mParameters;
489
490    struct Accumulator {
491        enum {
492            FIELD_BTN_MOUSE = 1,
493            FIELD_REL_X = 2,
494            FIELD_REL_Y = 4,
495            FIELD_REL_WHEEL = 8,
496            FIELD_REL_HWHEEL = 16,
497        };
498
499        uint32_t fields;
500
501        bool btnMouse;
502        int32_t relX;
503        int32_t relY;
504        int32_t relWheel;
505        int32_t relHWheel;
506
507        inline void clear() {
508            fields = 0;
509        }
510    } mAccumulator;
511
512    int32_t mSources;
513    float mXScale;
514    float mYScale;
515    float mXPrecision;
516    float mYPrecision;
517
518    bool mHaveVWheel;
519    bool mHaveHWheel;
520    float mVWheelScale;
521    float mHWheelScale;
522
523    sp<PointerControllerInterface> mPointerController;
524
525    struct LockedState {
526        bool down;
527        nsecs_t downTime;
528    } mLocked;
529
530    void initializeLocked();
531
532    void configureParameters();
533    void dumpParameters(String8& dump);
534
535    void sync(nsecs_t when);
536};
537
538
539class TouchInputMapper : public InputMapper {
540public:
541    TouchInputMapper(InputDevice* device);
542    virtual ~TouchInputMapper();
543
544    virtual uint32_t getSources();
545    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
546    virtual void dump(String8& dump);
547    virtual void configure();
548    virtual void reset();
549
550    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
551    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
552    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
553            const int32_t* keyCodes, uint8_t* outFlags);
554
555protected:
556    Mutex mLock;
557
558    struct VirtualKey {
559        int32_t keyCode;
560        int32_t scanCode;
561        uint32_t flags;
562
563        // computed hit box, specified in touch screen coords based on known display size
564        int32_t hitLeft;
565        int32_t hitTop;
566        int32_t hitRight;
567        int32_t hitBottom;
568
569        inline bool isHit(int32_t x, int32_t y) const {
570            return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
571        }
572    };
573
574    // Raw data for a single pointer.
575    struct PointerData {
576        uint32_t id;
577        int32_t x;
578        int32_t y;
579        int32_t pressure;
580        int32_t touchMajor;
581        int32_t touchMinor;
582        int32_t toolMajor;
583        int32_t toolMinor;
584        int32_t orientation;
585
586        inline bool operator== (const PointerData& other) const {
587            return id == other.id
588                    && x == other.x
589                    && y == other.y
590                    && pressure == other.pressure
591                    && touchMajor == other.touchMajor
592                    && touchMinor == other.touchMinor
593                    && toolMajor == other.toolMajor
594                    && toolMinor == other.toolMinor
595                    && orientation == other.orientation;
596        }
597        inline bool operator!= (const PointerData& other) const {
598            return !(*this == other);
599        }
600    };
601
602    // Raw data for a collection of pointers including a pointer id mapping table.
603    struct TouchData {
604        uint32_t pointerCount;
605        PointerData pointers[MAX_POINTERS];
606        BitSet32 idBits;
607        uint32_t idToIndex[MAX_POINTER_ID + 1];
608
609        void copyFrom(const TouchData& other) {
610            pointerCount = other.pointerCount;
611            idBits = other.idBits;
612
613            for (uint32_t i = 0; i < pointerCount; i++) {
614                pointers[i] = other.pointers[i];
615
616                int id = pointers[i].id;
617                idToIndex[id] = other.idToIndex[id];
618            }
619        }
620
621        inline void clear() {
622            pointerCount = 0;
623            idBits.clear();
624        }
625    };
626
627    // Input sources supported by the device.
628    int32_t mSources;
629
630    // Immutable configuration parameters.
631    struct Parameters {
632        enum DeviceType {
633            DEVICE_TYPE_TOUCH_SCREEN,
634            DEVICE_TYPE_TOUCH_PAD,
635        };
636
637        DeviceType deviceType;
638        int32_t associatedDisplayId;
639        bool orientationAware;
640
641        bool useBadTouchFilter;
642        bool useJumpyTouchFilter;
643        bool useAveragingTouchFilter;
644        nsecs_t virtualKeyQuietTime;
645    } mParameters;
646
647    // Immutable calibration parameters in parsed form.
648    struct Calibration {
649        // Position
650        bool haveXOrigin;
651        int32_t xOrigin;
652        bool haveYOrigin;
653        int32_t yOrigin;
654        bool haveXScale;
655        float xScale;
656        bool haveYScale;
657        float yScale;
658
659        // Touch Size
660        enum TouchSizeCalibration {
661            TOUCH_SIZE_CALIBRATION_DEFAULT,
662            TOUCH_SIZE_CALIBRATION_NONE,
663            TOUCH_SIZE_CALIBRATION_GEOMETRIC,
664            TOUCH_SIZE_CALIBRATION_PRESSURE,
665        };
666
667        TouchSizeCalibration touchSizeCalibration;
668
669        // Tool Size
670        enum ToolSizeCalibration {
671            TOOL_SIZE_CALIBRATION_DEFAULT,
672            TOOL_SIZE_CALIBRATION_NONE,
673            TOOL_SIZE_CALIBRATION_GEOMETRIC,
674            TOOL_SIZE_CALIBRATION_LINEAR,
675            TOOL_SIZE_CALIBRATION_AREA,
676        };
677
678        ToolSizeCalibration toolSizeCalibration;
679        bool haveToolSizeLinearScale;
680        float toolSizeLinearScale;
681        bool haveToolSizeLinearBias;
682        float toolSizeLinearBias;
683        bool haveToolSizeAreaScale;
684        float toolSizeAreaScale;
685        bool haveToolSizeAreaBias;
686        float toolSizeAreaBias;
687        bool haveToolSizeIsSummed;
688        bool toolSizeIsSummed;
689
690        // Pressure
691        enum PressureCalibration {
692            PRESSURE_CALIBRATION_DEFAULT,
693            PRESSURE_CALIBRATION_NONE,
694            PRESSURE_CALIBRATION_PHYSICAL,
695            PRESSURE_CALIBRATION_AMPLITUDE,
696        };
697        enum PressureSource {
698            PRESSURE_SOURCE_DEFAULT,
699            PRESSURE_SOURCE_PRESSURE,
700            PRESSURE_SOURCE_TOUCH,
701        };
702
703        PressureCalibration pressureCalibration;
704        PressureSource pressureSource;
705        bool havePressureScale;
706        float pressureScale;
707
708        // Size
709        enum SizeCalibration {
710            SIZE_CALIBRATION_DEFAULT,
711            SIZE_CALIBRATION_NONE,
712            SIZE_CALIBRATION_NORMALIZED,
713        };
714
715        SizeCalibration sizeCalibration;
716
717        // Orientation
718        enum OrientationCalibration {
719            ORIENTATION_CALIBRATION_DEFAULT,
720            ORIENTATION_CALIBRATION_NONE,
721            ORIENTATION_CALIBRATION_INTERPOLATED,
722            ORIENTATION_CALIBRATION_VECTOR,
723        };
724
725        OrientationCalibration orientationCalibration;
726    } mCalibration;
727
728    // Raw axis information from the driver.
729    struct RawAxes {
730        RawAbsoluteAxisInfo x;
731        RawAbsoluteAxisInfo y;
732        RawAbsoluteAxisInfo pressure;
733        RawAbsoluteAxisInfo touchMajor;
734        RawAbsoluteAxisInfo touchMinor;
735        RawAbsoluteAxisInfo toolMajor;
736        RawAbsoluteAxisInfo toolMinor;
737        RawAbsoluteAxisInfo orientation;
738    } mRawAxes;
739
740    // Current and previous touch sample data.
741    TouchData mCurrentTouch;
742    TouchData mLastTouch;
743
744    // The time the primary pointer last went down.
745    nsecs_t mDownTime;
746
747    struct LockedState {
748        Vector<VirtualKey> virtualKeys;
749
750        // The surface orientation and width and height set by configureSurfaceLocked().
751        int32_t surfaceOrientation;
752        int32_t surfaceWidth, surfaceHeight;
753
754        // Translation and scaling factors, orientation-independent.
755        int32_t xOrigin;
756        float xScale;
757        float xPrecision;
758
759        int32_t yOrigin;
760        float yScale;
761        float yPrecision;
762
763        float geometricScale;
764
765        float toolSizeLinearScale;
766        float toolSizeLinearBias;
767        float toolSizeAreaScale;
768        float toolSizeAreaBias;
769
770        float pressureScale;
771
772        float sizeScale;
773
774        float orientationScale;
775
776        // Oriented motion ranges for input device info.
777        struct OrientedRanges {
778            InputDeviceInfo::MotionRange x;
779            InputDeviceInfo::MotionRange y;
780
781            bool havePressure;
782            InputDeviceInfo::MotionRange pressure;
783
784            bool haveSize;
785            InputDeviceInfo::MotionRange size;
786
787            bool haveTouchSize;
788            InputDeviceInfo::MotionRange touchMajor;
789            InputDeviceInfo::MotionRange touchMinor;
790
791            bool haveToolSize;
792            InputDeviceInfo::MotionRange toolMajor;
793            InputDeviceInfo::MotionRange toolMinor;
794
795            bool haveOrientation;
796            InputDeviceInfo::MotionRange orientation;
797        } orientedRanges;
798
799        // Oriented dimensions and precision.
800        float orientedSurfaceWidth, orientedSurfaceHeight;
801        float orientedXPrecision, orientedYPrecision;
802
803        struct CurrentVirtualKeyState {
804            bool down;
805            nsecs_t downTime;
806            int32_t keyCode;
807            int32_t scanCode;
808        } currentVirtualKey;
809    } mLocked;
810
811    virtual void configureParameters();
812    virtual void dumpParameters(String8& dump);
813    virtual void configureRawAxes();
814    virtual void dumpRawAxes(String8& dump);
815    virtual bool configureSurfaceLocked();
816    virtual void dumpSurfaceLocked(String8& dump);
817    virtual void configureVirtualKeysLocked();
818    virtual void dumpVirtualKeysLocked(String8& dump);
819    virtual void parseCalibration();
820    virtual void resolveCalibration();
821    virtual void dumpCalibration(String8& dump);
822
823    enum TouchResult {
824        // Dispatch the touch normally.
825        DISPATCH_TOUCH,
826        // Do not dispatch the touch, but keep tracking the current stroke.
827        SKIP_TOUCH,
828        // Do not dispatch the touch, and drop all information associated with the current stoke
829        // so the next movement will appear as a new down.
830        DROP_STROKE
831    };
832
833    void syncTouch(nsecs_t when, bool havePointerIds);
834
835private:
836    /* Maximum number of historical samples to average. */
837    static const uint32_t AVERAGING_HISTORY_SIZE = 5;
838
839    /* Slop distance for jumpy pointer detection.
840     * The vertical range of the screen divided by this is our epsilon value. */
841    static const uint32_t JUMPY_EPSILON_DIVISOR = 212;
842
843    /* Number of jumpy points to drop for touchscreens that need it. */
844    static const uint32_t JUMPY_TRANSITION_DROPS = 3;
845    static const uint32_t JUMPY_DROP_LIMIT = 3;
846
847    /* Maximum squared distance for averaging.
848     * If moving farther than this, turn of averaging to avoid lag in response. */
849    static const uint64_t AVERAGING_DISTANCE_LIMIT = 75 * 75;
850
851    struct AveragingTouchFilterState {
852        // Individual history tracks are stored by pointer id
853        uint32_t historyStart[MAX_POINTERS];
854        uint32_t historyEnd[MAX_POINTERS];
855        struct {
856            struct {
857                int32_t x;
858                int32_t y;
859                int32_t pressure;
860            } pointers[MAX_POINTERS];
861        } historyData[AVERAGING_HISTORY_SIZE];
862    } mAveragingTouchFilter;
863
864    struct JumpyTouchFilterState {
865        uint32_t jumpyPointsDropped;
866    } mJumpyTouchFilter;
867
868    struct PointerDistanceHeapElement {
869        uint32_t currentPointerIndex : 8;
870        uint32_t lastPointerIndex : 8;
871        uint64_t distance : 48; // squared distance
872    };
873
874    void initializeLocked();
875
876    TouchResult consumeOffScreenTouches(nsecs_t when, uint32_t policyFlags);
877    void dispatchTouches(nsecs_t when, uint32_t policyFlags);
878    void dispatchTouch(nsecs_t when, uint32_t policyFlags, TouchData* touch,
879            BitSet32 idBits, uint32_t changedId, uint32_t pointerCount,
880            int32_t motionEventAction);
881    void detectGestures(nsecs_t when);
882
883    bool isPointInsideSurfaceLocked(int32_t x, int32_t y);
884    const VirtualKey* findVirtualKeyHitLocked(int32_t x, int32_t y);
885
886    bool applyBadTouchFilter();
887    bool applyJumpyTouchFilter();
888    void applyAveragingTouchFilter();
889    void calculatePointerIds();
890};
891
892
893class SingleTouchInputMapper : public TouchInputMapper {
894public:
895    SingleTouchInputMapper(InputDevice* device);
896    virtual ~SingleTouchInputMapper();
897
898    virtual void reset();
899    virtual void process(const RawEvent* rawEvent);
900
901protected:
902    virtual void configureRawAxes();
903
904private:
905    struct Accumulator {
906        enum {
907            FIELD_BTN_TOUCH = 1,
908            FIELD_ABS_X = 2,
909            FIELD_ABS_Y = 4,
910            FIELD_ABS_PRESSURE = 8,
911            FIELD_ABS_TOOL_WIDTH = 16
912        };
913
914        uint32_t fields;
915
916        bool btnTouch;
917        int32_t absX;
918        int32_t absY;
919        int32_t absPressure;
920        int32_t absToolWidth;
921
922        inline void clear() {
923            fields = 0;
924        }
925    } mAccumulator;
926
927    bool mDown;
928    int32_t mX;
929    int32_t mY;
930    int32_t mPressure;
931    int32_t mToolWidth;
932
933    void initialize();
934
935    void sync(nsecs_t when);
936};
937
938
939class MultiTouchInputMapper : public TouchInputMapper {
940public:
941    MultiTouchInputMapper(InputDevice* device);
942    virtual ~MultiTouchInputMapper();
943
944    virtual void reset();
945    virtual void process(const RawEvent* rawEvent);
946
947protected:
948    virtual void configureRawAxes();
949
950private:
951    struct Accumulator {
952        enum {
953            FIELD_ABS_MT_POSITION_X = 1,
954            FIELD_ABS_MT_POSITION_Y = 2,
955            FIELD_ABS_MT_TOUCH_MAJOR = 4,
956            FIELD_ABS_MT_TOUCH_MINOR = 8,
957            FIELD_ABS_MT_WIDTH_MAJOR = 16,
958            FIELD_ABS_MT_WIDTH_MINOR = 32,
959            FIELD_ABS_MT_ORIENTATION = 64,
960            FIELD_ABS_MT_TRACKING_ID = 128,
961            FIELD_ABS_MT_PRESSURE = 256,
962        };
963
964        uint32_t pointerCount;
965        struct Pointer {
966            uint32_t fields;
967
968            int32_t absMTPositionX;
969            int32_t absMTPositionY;
970            int32_t absMTTouchMajor;
971            int32_t absMTTouchMinor;
972            int32_t absMTWidthMajor;
973            int32_t absMTWidthMinor;
974            int32_t absMTOrientation;
975            int32_t absMTTrackingId;
976            int32_t absMTPressure;
977
978            inline void clear() {
979                fields = 0;
980            }
981        } pointers[MAX_POINTERS + 1]; // + 1 to remove the need for extra range checks
982
983        inline void clear() {
984            pointerCount = 0;
985            pointers[0].clear();
986        }
987    } mAccumulator;
988
989    void initialize();
990
991    void sync(nsecs_t when);
992};
993
994
995class JoystickInputMapper : public InputMapper {
996public:
997    JoystickInputMapper(InputDevice* device);
998    virtual ~JoystickInputMapper();
999
1000    virtual uint32_t getSources();
1001    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1002    virtual void dump(String8& dump);
1003    virtual void configure();
1004    virtual void reset();
1005    virtual void process(const RawEvent* rawEvent);
1006
1007private:
1008    struct Axis {
1009        RawAbsoluteAxisInfo rawAxisInfo;
1010
1011        int32_t axis;  // axis id
1012        bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1013
1014        float scale;   // scale factor from raw to normalized values
1015        float offset;  // offset to add after scaling for normalization
1016
1017        float min;     // normalized inclusive minimum
1018        float max;     // normalized inclusive maximum
1019        float flat;    // normalized flat region size
1020        float fuzz;    // normalized error tolerance
1021
1022        float oldValue; // previous value
1023        float newValue; // most recent value
1024
1025        float filter;  // filter out small variations of this size
1026
1027        void initialize(const RawAbsoluteAxisInfo& rawAxisInfo,
1028                int32_t axis, bool explicitlyMapped, float scale, float offset,
1029                float min, float max, float flat, float fuzz) {
1030            this->rawAxisInfo = rawAxisInfo;
1031            this->axis = axis;
1032            this->explicitlyMapped = explicitlyMapped;
1033            this->scale = scale;
1034            this->offset = offset;
1035            this->min = min;
1036            this->max = max;
1037            this->flat = flat;
1038            this->fuzz = fuzz;
1039            this->filter = 0;
1040            this->oldValue = 0;
1041            this->newValue = 0;
1042        }
1043    };
1044
1045    // Axes indexed by raw ABS_* axis index.
1046    KeyedVector<int32_t, Axis> mAxes;
1047
1048    void sync(nsecs_t when, bool force);
1049
1050    bool haveAxis(int32_t axis);
1051    void pruneAxes(bool ignoreExplicitlyMappedAxes);
1052    bool haveAxesChangedSignificantly();
1053
1054    static bool isCenteredAxis(int32_t axis);
1055};
1056
1057} // namespace android
1058
1059#endif // _UI_INPUT_READER_H
1060