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