InputReader.h revision 71b16e81f9cbf2e288611f32c43ea7fb4a331fcf
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 "PointerControllerInterface.h"
22#include "InputListener.h"
23
24#include <input/Input.h>
25#include <input/VelocityControl.h>
26#include <input/VelocityTracker.h>
27#include <ui/DisplayInfo.h>
28#include <utils/KeyedVector.h>
29#include <utils/threads.h>
30#include <utils/Timers.h>
31#include <utils/RefBase.h>
32#include <utils/String8.h>
33#include <utils/BitSet.h>
34
35#include <stddef.h>
36#include <unistd.h>
37
38// Maximum supported size of a vibration pattern.
39// Must be at least 2.
40#define MAX_VIBRATE_PATTERN_SIZE 100
41
42// Maximum allowable delay value in a vibration pattern before
43// which the delay will be truncated.
44#define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL)
45
46namespace android {
47
48class InputDevice;
49class InputMapper;
50
51/*
52 * Describes how coordinates are mapped on a physical display.
53 * See com.android.server.display.DisplayViewport.
54 */
55struct DisplayViewport {
56    int32_t displayId; // -1 if invalid
57    int32_t orientation;
58    int32_t logicalLeft;
59    int32_t logicalTop;
60    int32_t logicalRight;
61    int32_t logicalBottom;
62    int32_t physicalLeft;
63    int32_t physicalTop;
64    int32_t physicalRight;
65    int32_t physicalBottom;
66    int32_t deviceWidth;
67    int32_t deviceHeight;
68
69    DisplayViewport() :
70            displayId(ADISPLAY_ID_NONE), orientation(DISPLAY_ORIENTATION_0),
71            logicalLeft(0), logicalTop(0), logicalRight(0), logicalBottom(0),
72            physicalLeft(0), physicalTop(0), physicalRight(0), physicalBottom(0),
73            deviceWidth(0), deviceHeight(0) {
74    }
75
76    bool operator==(const DisplayViewport& other) const {
77        return displayId == other.displayId
78                && orientation == other.orientation
79                && logicalLeft == other.logicalLeft
80                && logicalTop == other.logicalTop
81                && logicalRight == other.logicalRight
82                && logicalBottom == other.logicalBottom
83                && physicalLeft == other.physicalLeft
84                && physicalTop == other.physicalTop
85                && physicalRight == other.physicalRight
86                && physicalBottom == other.physicalBottom
87                && deviceWidth == other.deviceWidth
88                && deviceHeight == other.deviceHeight;
89    }
90
91    bool operator!=(const DisplayViewport& other) const {
92        return !(*this == other);
93    }
94
95    inline bool isValid() const {
96        return displayId >= 0;
97    }
98
99    void setNonDisplayViewport(int32_t width, int32_t height) {
100        displayId = ADISPLAY_ID_NONE;
101        orientation = DISPLAY_ORIENTATION_0;
102        logicalLeft = 0;
103        logicalTop = 0;
104        logicalRight = width;
105        logicalBottom = height;
106        physicalLeft = 0;
107        physicalTop = 0;
108        physicalRight = width;
109        physicalBottom = height;
110        deviceWidth = width;
111        deviceHeight = height;
112    }
113};
114
115/*
116 * Input reader configuration.
117 *
118 * Specifies various options that modify the behavior of the input reader.
119 */
120struct InputReaderConfiguration {
121    // Describes changes that have occurred.
122    enum {
123        // The pointer speed changed.
124        CHANGE_POINTER_SPEED = 1 << 0,
125
126        // The pointer gesture control changed.
127        CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1,
128
129        // The display size or orientation changed.
130        CHANGE_DISPLAY_INFO = 1 << 2,
131
132        // The visible touches option changed.
133        CHANGE_SHOW_TOUCHES = 1 << 3,
134
135        // The keyboard layouts must be reloaded.
136        CHANGE_KEYBOARD_LAYOUTS = 1 << 4,
137
138        // The device name alias supplied by the may have changed for some devices.
139        CHANGE_DEVICE_ALIAS = 1 << 5,
140
141        // The location calibration matrix changed.
142        TOUCH_AFFINE_TRANSFORMATION = 1 << 6,
143
144        // All devices must be reopened.
145        CHANGE_MUST_REOPEN = 1 << 31,
146    };
147
148    // Gets the amount of time to disable virtual keys after the screen is touched
149    // in order to filter out accidental virtual key presses due to swiping gestures
150    // or taps near the edge of the display.  May be 0 to disable the feature.
151    nsecs_t virtualKeyQuietTime;
152
153    // The excluded device names for the platform.
154    // Devices with these names will be ignored.
155    Vector<String8> excludedDeviceNames;
156
157    // Velocity control parameters for mouse pointer movements.
158    VelocityControlParameters pointerVelocityControlParameters;
159
160    // Velocity control parameters for mouse wheel movements.
161    VelocityControlParameters wheelVelocityControlParameters;
162
163    // True if pointer gestures are enabled.
164    bool pointerGesturesEnabled;
165
166    // Quiet time between certain pointer gesture transitions.
167    // Time to allow for all fingers or buttons to settle into a stable state before
168    // starting a new gesture.
169    nsecs_t pointerGestureQuietInterval;
170
171    // The minimum speed that a pointer must travel for us to consider switching the active
172    // touch pointer to it during a drag.  This threshold is set to avoid switching due
173    // to noise from a finger resting on the touch pad (perhaps just pressing it down).
174    float pointerGestureDragMinSwitchSpeed; // in pixels per second
175
176    // Tap gesture delay time.
177    // The time between down and up must be less than this to be considered a tap.
178    nsecs_t pointerGestureTapInterval;
179
180    // Tap drag gesture delay time.
181    // The time between the previous tap's up and the next down must be less than
182    // this to be considered a drag.  Otherwise, the previous tap is finished and a
183    // new tap begins.
184    //
185    // Note that the previous tap will be held down for this entire duration so this
186    // interval must be shorter than the long press timeout.
187    nsecs_t pointerGestureTapDragInterval;
188
189    // The distance in pixels that the pointer is allowed to move from initial down
190    // to up and still be called a tap.
191    float pointerGestureTapSlop; // in pixels
192
193    // Time after the first touch points go down to settle on an initial centroid.
194    // This is intended to be enough time to handle cases where the user puts down two
195    // fingers at almost but not quite exactly the same time.
196    nsecs_t pointerGestureMultitouchSettleInterval;
197
198    // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
199    // at least two pointers have moved at least this far from their starting place.
200    float pointerGestureMultitouchMinDistance; // in pixels
201
202    // The transition from PRESS to SWIPE gesture mode can only occur when the
203    // cosine of the angle between the two vectors is greater than or equal to than this value
204    // which indicates that the vectors are oriented in the same direction.
205    // When the vectors are oriented in the exactly same direction, the cosine is 1.0.
206    // (In exactly opposite directions, the cosine is -1.0.)
207    float pointerGestureSwipeTransitionAngleCosine;
208
209    // The transition from PRESS to SWIPE gesture mode can only occur when the
210    // fingers are no more than this far apart relative to the diagonal size of
211    // the touch pad.  For example, a ratio of 0.5 means that the fingers must be
212    // no more than half the diagonal size of the touch pad apart.
213    float pointerGestureSwipeMaxWidthRatio;
214
215    // The gesture movement speed factor relative to the size of the display.
216    // Movement speed applies when the fingers are moving in the same direction.
217    // Without acceleration, a full swipe of the touch pad diagonal in movement mode
218    // will cover this portion of the display diagonal.
219    float pointerGestureMovementSpeedRatio;
220
221    // The gesture zoom speed factor relative to the size of the display.
222    // Zoom speed applies when the fingers are mostly moving relative to each other
223    // to execute a scale gesture or similar.
224    // Without acceleration, a full swipe of the touch pad diagonal in zoom mode
225    // will cover this portion of the display diagonal.
226    float pointerGestureZoomSpeedRatio;
227
228    // True to show the location of touches on the touch screen as spots.
229    bool showTouches;
230
231    InputReaderConfiguration() :
232            virtualKeyQuietTime(0),
233            pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f),
234            wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f),
235            pointerGesturesEnabled(true),
236            pointerGestureQuietInterval(100 * 1000000LL), // 100 ms
237            pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second
238            pointerGestureTapInterval(150 * 1000000LL), // 150 ms
239            pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms
240            pointerGestureTapSlop(10.0f), // 10 pixels
241            pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms
242            pointerGestureMultitouchMinDistance(15), // 15 pixels
243            pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees
244            pointerGestureSwipeMaxWidthRatio(0.25f),
245            pointerGestureMovementSpeedRatio(0.8f),
246            pointerGestureZoomSpeedRatio(0.3f),
247            showTouches(false) { }
248
249    bool getDisplayInfo(bool external, DisplayViewport* outViewport) const;
250    void setDisplayInfo(bool external, const DisplayViewport& viewport);
251
252private:
253    DisplayViewport mInternalDisplay;
254    DisplayViewport mExternalDisplay;
255};
256
257
258struct TouchAffineTransformation {
259    float x_scale;
260    float x_ymix;
261    float x_offset;
262    float y_xmix;
263    float y_scale;
264    float y_offset;
265
266    TouchAffineTransformation() :
267        x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f),
268        y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) {
269    }
270
271    TouchAffineTransformation(float xscale, float xymix, float xoffset,
272            float yxmix, float yscale, float yoffset) :
273        x_scale(xscale), x_ymix(xymix), x_offset(xoffset),
274        y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) {
275    }
276
277    void applyTo(float& x, float& y) const;
278};
279
280
281/*
282 * Input reader policy interface.
283 *
284 * The input reader policy is used by the input reader to interact with the Window Manager
285 * and other system components.
286 *
287 * The actual implementation is partially supported by callbacks into the DVM
288 * via JNI.  This interface is also mocked in the unit tests.
289 *
290 * These methods must NOT re-enter the input reader since they may be called while
291 * holding the input reader lock.
292 */
293class InputReaderPolicyInterface : public virtual RefBase {
294protected:
295    InputReaderPolicyInterface() { }
296    virtual ~InputReaderPolicyInterface() { }
297
298public:
299    /* Gets the input reader configuration. */
300    virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0;
301
302    /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */
303    virtual sp<PointerControllerInterface> obtainPointerController(int32_t deviceId) = 0;
304
305    /* Notifies the input reader policy that some input devices have changed
306     * and provides information about all current input devices.
307     */
308    virtual void notifyInputDevicesChanged(const Vector<InputDeviceInfo>& inputDevices) = 0;
309
310    /* Gets the keyboard layout for a particular input device. */
311    virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay(
312            const InputDeviceIdentifier& identifier) = 0;
313
314    /* Gets a user-supplied alias for a particular input device, or an empty string if none. */
315    virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier) = 0;
316
317    /* Gets the affine calibration associated with the specified device. */
318    virtual TouchAffineTransformation getTouchAffineTransformation(
319            const String8& inputDeviceDescriptor, int32_t surfaceRotation) = 0;
320};
321
322
323/* Processes raw input events and sends cooked event data to an input listener. */
324class InputReaderInterface : public virtual RefBase {
325protected:
326    InputReaderInterface() { }
327    virtual ~InputReaderInterface() { }
328
329public:
330    /* Dumps the state of the input reader.
331     *
332     * This method may be called on any thread (usually by the input manager). */
333    virtual void dump(String8& dump) = 0;
334
335    /* Called by the heatbeat to ensures that the reader has not deadlocked. */
336    virtual void monitor() = 0;
337
338    /* Runs a single iteration of the processing loop.
339     * Nominally reads and processes one incoming message from the EventHub.
340     *
341     * This method should be called on the input reader thread.
342     */
343    virtual void loopOnce() = 0;
344
345    /* Gets information about all input devices.
346     *
347     * This method may be called on any thread (usually by the input manager).
348     */
349    virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices) = 0;
350
351    /* Query current input state. */
352    virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
353            int32_t scanCode) = 0;
354    virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
355            int32_t keyCode) = 0;
356    virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
357            int32_t sw) = 0;
358
359    /* Determine whether physical keys exist for the given framework-domain key codes. */
360    virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
361            size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0;
362
363    /* Requests that a reconfiguration of all input devices.
364     * The changes flag is a bitfield that indicates what has changed and whether
365     * the input devices must all be reopened. */
366    virtual void requestRefreshConfiguration(uint32_t changes) = 0;
367
368    /* Controls the vibrator of a particular input device. */
369    virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
370            ssize_t repeat, int32_t token) = 0;
371    virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0;
372};
373
374
375/* Internal interface used by individual input devices to access global input device state
376 * and parameters maintained by the input reader.
377 */
378class InputReaderContext {
379public:
380    InputReaderContext() { }
381    virtual ~InputReaderContext() { }
382
383    virtual void updateGlobalMetaState() = 0;
384    virtual int32_t getGlobalMetaState() = 0;
385
386    virtual void disableVirtualKeysUntil(nsecs_t time) = 0;
387    virtual bool shouldDropVirtualKey(nsecs_t now,
388            InputDevice* device, int32_t keyCode, int32_t scanCode) = 0;
389
390    virtual void fadePointer() = 0;
391
392    virtual void requestTimeoutAtTime(nsecs_t when) = 0;
393    virtual int32_t bumpGeneration() = 0;
394
395    virtual InputReaderPolicyInterface* getPolicy() = 0;
396    virtual InputListenerInterface* getListener() = 0;
397    virtual EventHubInterface* getEventHub() = 0;
398};
399
400
401/* The input reader reads raw event data from the event hub and processes it into input events
402 * that it sends to the input listener.  Some functions of the input reader, such as early
403 * event filtering in low power states, are controlled by a separate policy object.
404 *
405 * The InputReader owns a collection of InputMappers.  Most of the work it does happens
406 * on the input reader thread but the InputReader can receive queries from other system
407 * components running on arbitrary threads.  To keep things manageable, the InputReader
408 * uses a single Mutex to guard its state.  The Mutex may be held while calling into the
409 * EventHub or the InputReaderPolicy but it is never held while calling into the
410 * InputListener.
411 */
412class InputReader : public InputReaderInterface {
413public:
414    InputReader(const sp<EventHubInterface>& eventHub,
415            const sp<InputReaderPolicyInterface>& policy,
416            const sp<InputListenerInterface>& listener);
417    virtual ~InputReader();
418
419    virtual void dump(String8& dump);
420    virtual void monitor();
421
422    virtual void loopOnce();
423
424    virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices);
425
426    virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
427            int32_t scanCode);
428    virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
429            int32_t keyCode);
430    virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
431            int32_t sw);
432
433    virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
434            size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags);
435
436    virtual void requestRefreshConfiguration(uint32_t changes);
437
438    virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
439            ssize_t repeat, int32_t token);
440    virtual void cancelVibrate(int32_t deviceId, int32_t token);
441
442protected:
443    // These members are protected so they can be instrumented by test cases.
444    virtual InputDevice* createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
445            const InputDeviceIdentifier& identifier, uint32_t classes);
446
447    class ContextImpl : public InputReaderContext {
448        InputReader* mReader;
449
450    public:
451        ContextImpl(InputReader* reader);
452
453        virtual void updateGlobalMetaState();
454        virtual int32_t getGlobalMetaState();
455        virtual void disableVirtualKeysUntil(nsecs_t time);
456        virtual bool shouldDropVirtualKey(nsecs_t now,
457                InputDevice* device, int32_t keyCode, int32_t scanCode);
458        virtual void fadePointer();
459        virtual void requestTimeoutAtTime(nsecs_t when);
460        virtual int32_t bumpGeneration();
461        virtual InputReaderPolicyInterface* getPolicy();
462        virtual InputListenerInterface* getListener();
463        virtual EventHubInterface* getEventHub();
464    } mContext;
465
466    friend class ContextImpl;
467
468private:
469    Mutex mLock;
470
471    Condition mReaderIsAliveCondition;
472
473    sp<EventHubInterface> mEventHub;
474    sp<InputReaderPolicyInterface> mPolicy;
475    sp<QueuedInputListener> mQueuedListener;
476
477    InputReaderConfiguration mConfig;
478
479    // The event queue.
480    static const int EVENT_BUFFER_SIZE = 256;
481    RawEvent mEventBuffer[EVENT_BUFFER_SIZE];
482
483    KeyedVector<int32_t, InputDevice*> mDevices;
484
485    // low-level input event decoding and device management
486    void processEventsLocked(const RawEvent* rawEvents, size_t count);
487
488    void addDeviceLocked(nsecs_t when, int32_t deviceId);
489    void removeDeviceLocked(nsecs_t when, int32_t deviceId);
490    void processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count);
491    void timeoutExpiredLocked(nsecs_t when);
492
493    void handleConfigurationChangedLocked(nsecs_t when);
494
495    int32_t mGlobalMetaState;
496    void updateGlobalMetaStateLocked();
497    int32_t getGlobalMetaStateLocked();
498
499    void fadePointerLocked();
500
501    int32_t mGeneration;
502    int32_t bumpGenerationLocked();
503
504    void getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices);
505
506    nsecs_t mDisableVirtualKeysTimeout;
507    void disableVirtualKeysUntilLocked(nsecs_t time);
508    bool shouldDropVirtualKeyLocked(nsecs_t now,
509            InputDevice* device, int32_t keyCode, int32_t scanCode);
510
511    nsecs_t mNextTimeout;
512    void requestTimeoutAtTimeLocked(nsecs_t when);
513
514    uint32_t mConfigurationChangesToRefresh;
515    void refreshConfigurationLocked(uint32_t changes);
516
517    // state queries
518    typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
519    int32_t getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
520            GetStateFunc getStateFunc);
521    bool markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
522            const int32_t* keyCodes, uint8_t* outFlags);
523};
524
525
526/* Reads raw events from the event hub and processes them, endlessly. */
527class InputReaderThread : public Thread {
528public:
529    InputReaderThread(const sp<InputReaderInterface>& reader);
530    virtual ~InputReaderThread();
531
532private:
533    sp<InputReaderInterface> mReader;
534
535    virtual bool threadLoop();
536};
537
538
539/* Represents the state of a single input device. */
540class InputDevice {
541public:
542    InputDevice(InputReaderContext* context, int32_t id, int32_t generation, int32_t
543            controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes);
544    ~InputDevice();
545
546    inline InputReaderContext* getContext() { return mContext; }
547    inline int32_t getId() const { return mId; }
548    inline int32_t getControllerNumber() const { return mControllerNumber; }
549    inline int32_t getGeneration() const { return mGeneration; }
550    inline const String8& getName() const { return mIdentifier.name; }
551    inline const String8& getDescriptor() { return mIdentifier.descriptor; }
552    inline uint32_t getClasses() const { return mClasses; }
553    inline uint32_t getSources() const { return mSources; }
554
555    inline bool isExternal() { return mIsExternal; }
556    inline void setExternal(bool external) { mIsExternal = external; }
557
558    inline bool isIgnored() { return mMappers.isEmpty(); }
559
560    void dump(String8& dump);
561    void addMapper(InputMapper* mapper);
562    void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
563    void reset(nsecs_t when);
564    void process(const RawEvent* rawEvents, size_t count);
565    void timeoutExpired(nsecs_t when);
566
567    void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
568    int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
569    int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
570    int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
571    bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
572            const int32_t* keyCodes, uint8_t* outFlags);
573    void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token);
574    void cancelVibrate(int32_t token);
575
576    int32_t getMetaState();
577
578    void fadePointer();
579
580    void bumpGeneration();
581
582    void notifyReset(nsecs_t when);
583
584    inline const PropertyMap& getConfiguration() { return mConfiguration; }
585    inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
586
587    bool hasKey(int32_t code) {
588        return getEventHub()->hasScanCode(mId, code);
589    }
590
591    bool hasAbsoluteAxis(int32_t code) {
592        RawAbsoluteAxisInfo info;
593        getEventHub()->getAbsoluteAxisInfo(mId, code, &info);
594        return info.valid;
595    }
596
597    bool isKeyPressed(int32_t code) {
598        return getEventHub()->getScanCodeState(mId, code) == AKEY_STATE_DOWN;
599    }
600
601    int32_t getAbsoluteAxisValue(int32_t code) {
602        int32_t value;
603        getEventHub()->getAbsoluteAxisValue(mId, code, &value);
604        return value;
605    }
606
607private:
608    InputReaderContext* mContext;
609    int32_t mId;
610    int32_t mGeneration;
611    int32_t mControllerNumber;
612    InputDeviceIdentifier mIdentifier;
613    String8 mAlias;
614    uint32_t mClasses;
615
616    Vector<InputMapper*> mMappers;
617
618    uint32_t mSources;
619    bool mIsExternal;
620    bool mDropUntilNextSync;
621
622    typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
623    int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
624
625    PropertyMap mConfiguration;
626};
627
628
629/* Keeps track of the state of mouse or touch pad buttons. */
630class CursorButtonAccumulator {
631public:
632    CursorButtonAccumulator();
633    void reset(InputDevice* device);
634
635    void process(const RawEvent* rawEvent);
636
637    uint32_t getButtonState() const;
638
639private:
640    bool mBtnLeft;
641    bool mBtnRight;
642    bool mBtnMiddle;
643    bool mBtnBack;
644    bool mBtnSide;
645    bool mBtnForward;
646    bool mBtnExtra;
647    bool mBtnTask;
648
649    void clearButtons();
650};
651
652
653/* Keeps track of cursor movements. */
654
655class CursorMotionAccumulator {
656public:
657    CursorMotionAccumulator();
658    void reset(InputDevice* device);
659
660    void process(const RawEvent* rawEvent);
661    void finishSync();
662
663    inline int32_t getRelativeX() const { return mRelX; }
664    inline int32_t getRelativeY() const { return mRelY; }
665
666private:
667    int32_t mRelX;
668    int32_t mRelY;
669
670    void clearRelativeAxes();
671};
672
673
674/* Keeps track of cursor scrolling motions. */
675
676class CursorScrollAccumulator {
677public:
678    CursorScrollAccumulator();
679    void configure(InputDevice* device);
680    void reset(InputDevice* device);
681
682    void process(const RawEvent* rawEvent);
683    void finishSync();
684
685    inline bool haveRelativeVWheel() const { return mHaveRelWheel; }
686    inline bool haveRelativeHWheel() const { return mHaveRelHWheel; }
687
688    inline int32_t getRelativeX() const { return mRelX; }
689    inline int32_t getRelativeY() const { return mRelY; }
690    inline int32_t getRelativeVWheel() const { return mRelWheel; }
691    inline int32_t getRelativeHWheel() const { return mRelHWheel; }
692
693private:
694    bool mHaveRelWheel;
695    bool mHaveRelHWheel;
696
697    int32_t mRelX;
698    int32_t mRelY;
699    int32_t mRelWheel;
700    int32_t mRelHWheel;
701
702    void clearRelativeAxes();
703};
704
705
706/* Keeps track of the state of touch, stylus and tool buttons. */
707class TouchButtonAccumulator {
708public:
709    TouchButtonAccumulator();
710    void configure(InputDevice* device);
711    void reset(InputDevice* device);
712
713    void process(const RawEvent* rawEvent);
714
715    uint32_t getButtonState() const;
716    int32_t getToolType() const;
717    bool isToolActive() const;
718    bool isHovering() const;
719    bool hasStylus() const;
720
721private:
722    bool mHaveBtnTouch;
723    bool mHaveStylus;
724
725    bool mBtnTouch;
726    bool mBtnStylus;
727    bool mBtnStylus2;
728    bool mBtnToolFinger;
729    bool mBtnToolPen;
730    bool mBtnToolRubber;
731    bool mBtnToolBrush;
732    bool mBtnToolPencil;
733    bool mBtnToolAirbrush;
734    bool mBtnToolMouse;
735    bool mBtnToolLens;
736    bool mBtnToolDoubleTap;
737    bool mBtnToolTripleTap;
738    bool mBtnToolQuadTap;
739
740    void clearButtons();
741};
742
743
744/* Raw axis information from the driver. */
745struct RawPointerAxes {
746    RawAbsoluteAxisInfo x;
747    RawAbsoluteAxisInfo y;
748    RawAbsoluteAxisInfo pressure;
749    RawAbsoluteAxisInfo touchMajor;
750    RawAbsoluteAxisInfo touchMinor;
751    RawAbsoluteAxisInfo toolMajor;
752    RawAbsoluteAxisInfo toolMinor;
753    RawAbsoluteAxisInfo orientation;
754    RawAbsoluteAxisInfo distance;
755    RawAbsoluteAxisInfo tiltX;
756    RawAbsoluteAxisInfo tiltY;
757    RawAbsoluteAxisInfo trackingId;
758    RawAbsoluteAxisInfo slot;
759
760    RawPointerAxes();
761    void clear();
762};
763
764
765/* Raw data for a collection of pointers including a pointer id mapping table. */
766struct RawPointerData {
767    struct Pointer {
768        uint32_t id;
769        int32_t x;
770        int32_t y;
771        int32_t pressure;
772        int32_t touchMajor;
773        int32_t touchMinor;
774        int32_t toolMajor;
775        int32_t toolMinor;
776        int32_t orientation;
777        int32_t distance;
778        int32_t tiltX;
779        int32_t tiltY;
780        int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant
781        bool isHovering;
782    };
783
784    uint32_t pointerCount;
785    Pointer pointers[MAX_POINTERS];
786    BitSet32 hoveringIdBits, touchingIdBits;
787    uint32_t idToIndex[MAX_POINTER_ID + 1];
788
789    RawPointerData();
790    void clear();
791    void copyFrom(const RawPointerData& other);
792    void getCentroidOfTouchingPointers(float* outX, float* outY) const;
793
794    inline void markIdBit(uint32_t id, bool isHovering) {
795        if (isHovering) {
796            hoveringIdBits.markBit(id);
797        } else {
798            touchingIdBits.markBit(id);
799        }
800    }
801
802    inline void clearIdBits() {
803        hoveringIdBits.clear();
804        touchingIdBits.clear();
805    }
806
807    inline const Pointer& pointerForId(uint32_t id) const {
808        return pointers[idToIndex[id]];
809    }
810
811    inline bool isHovering(uint32_t pointerIndex) {
812        return pointers[pointerIndex].isHovering;
813    }
814};
815
816
817/* Cooked data for a collection of pointers including a pointer id mapping table. */
818struct CookedPointerData {
819    uint32_t pointerCount;
820    PointerProperties pointerProperties[MAX_POINTERS];
821    PointerCoords pointerCoords[MAX_POINTERS];
822    BitSet32 hoveringIdBits, touchingIdBits;
823    uint32_t idToIndex[MAX_POINTER_ID + 1];
824
825    CookedPointerData();
826    void clear();
827    void copyFrom(const CookedPointerData& other);
828
829    inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
830        return pointerCoords[idToIndex[id]];
831    }
832
833    inline bool isHovering(uint32_t pointerIndex) {
834        return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
835    }
836};
837
838
839/* Keeps track of the state of single-touch protocol. */
840class SingleTouchMotionAccumulator {
841public:
842    SingleTouchMotionAccumulator();
843
844    void process(const RawEvent* rawEvent);
845    void reset(InputDevice* device);
846
847    inline int32_t getAbsoluteX() const { return mAbsX; }
848    inline int32_t getAbsoluteY() const { return mAbsY; }
849    inline int32_t getAbsolutePressure() const { return mAbsPressure; }
850    inline int32_t getAbsoluteToolWidth() const { return mAbsToolWidth; }
851    inline int32_t getAbsoluteDistance() const { return mAbsDistance; }
852    inline int32_t getAbsoluteTiltX() const { return mAbsTiltX; }
853    inline int32_t getAbsoluteTiltY() const { return mAbsTiltY; }
854
855private:
856    int32_t mAbsX;
857    int32_t mAbsY;
858    int32_t mAbsPressure;
859    int32_t mAbsToolWidth;
860    int32_t mAbsDistance;
861    int32_t mAbsTiltX;
862    int32_t mAbsTiltY;
863
864    void clearAbsoluteAxes();
865};
866
867
868/* Keeps track of the state of multi-touch protocol. */
869class MultiTouchMotionAccumulator {
870public:
871    class Slot {
872    public:
873        inline bool isInUse() const { return mInUse; }
874        inline int32_t getX() const { return mAbsMTPositionX; }
875        inline int32_t getY() const { return mAbsMTPositionY; }
876        inline int32_t getTouchMajor() const { return mAbsMTTouchMajor; }
877        inline int32_t getTouchMinor() const {
878            return mHaveAbsMTTouchMinor ? mAbsMTTouchMinor : mAbsMTTouchMajor; }
879        inline int32_t getToolMajor() const { return mAbsMTWidthMajor; }
880        inline int32_t getToolMinor() const {
881            return mHaveAbsMTWidthMinor ? mAbsMTWidthMinor : mAbsMTWidthMajor; }
882        inline int32_t getOrientation() const { return mAbsMTOrientation; }
883        inline int32_t getTrackingId() const { return mAbsMTTrackingId; }
884        inline int32_t getPressure() const { return mAbsMTPressure; }
885        inline int32_t getDistance() const { return mAbsMTDistance; }
886        inline int32_t getToolType() const;
887
888    private:
889        friend class MultiTouchMotionAccumulator;
890
891        bool mInUse;
892        bool mHaveAbsMTTouchMinor;
893        bool mHaveAbsMTWidthMinor;
894        bool mHaveAbsMTToolType;
895
896        int32_t mAbsMTPositionX;
897        int32_t mAbsMTPositionY;
898        int32_t mAbsMTTouchMajor;
899        int32_t mAbsMTTouchMinor;
900        int32_t mAbsMTWidthMajor;
901        int32_t mAbsMTWidthMinor;
902        int32_t mAbsMTOrientation;
903        int32_t mAbsMTTrackingId;
904        int32_t mAbsMTPressure;
905        int32_t mAbsMTDistance;
906        int32_t mAbsMTToolType;
907
908        Slot();
909        void clear();
910    };
911
912    MultiTouchMotionAccumulator();
913    ~MultiTouchMotionAccumulator();
914
915    void configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol);
916    void reset(InputDevice* device);
917    void process(const RawEvent* rawEvent);
918    void finishSync();
919    bool hasStylus() const;
920
921    inline size_t getSlotCount() const { return mSlotCount; }
922    inline const Slot* getSlot(size_t index) const { return &mSlots[index]; }
923
924private:
925    int32_t mCurrentSlot;
926    Slot* mSlots;
927    size_t mSlotCount;
928    bool mUsingSlotsProtocol;
929    bool mHaveStylus;
930
931    void clearSlots(int32_t initialSlot);
932};
933
934
935/* An input mapper transforms raw input events into cooked event data.
936 * A single input device can have multiple associated input mappers in order to interpret
937 * different classes of events.
938 *
939 * InputMapper lifecycle:
940 * - create
941 * - configure with 0 changes
942 * - reset
943 * - process, process, process (may occasionally reconfigure with non-zero changes or reset)
944 * - reset
945 * - destroy
946 */
947class InputMapper {
948public:
949    InputMapper(InputDevice* device);
950    virtual ~InputMapper();
951
952    inline InputDevice* getDevice() { return mDevice; }
953    inline int32_t getDeviceId() { return mDevice->getId(); }
954    inline const String8 getDeviceName() { return mDevice->getName(); }
955    inline InputReaderContext* getContext() { return mContext; }
956    inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
957    inline InputListenerInterface* getListener() { return mContext->getListener(); }
958    inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
959
960    virtual uint32_t getSources() = 0;
961    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
962    virtual void dump(String8& dump);
963    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
964    virtual void reset(nsecs_t when);
965    virtual void process(const RawEvent* rawEvent) = 0;
966    virtual void timeoutExpired(nsecs_t when);
967
968    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
969    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
970    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
971    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
972            const int32_t* keyCodes, uint8_t* outFlags);
973    virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
974            int32_t token);
975    virtual void cancelVibrate(int32_t token);
976
977    virtual int32_t getMetaState();
978
979    virtual void fadePointer();
980
981protected:
982    InputDevice* mDevice;
983    InputReaderContext* mContext;
984
985    status_t getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo);
986    void bumpGeneration();
987
988    static void dumpRawAbsoluteAxisInfo(String8& dump,
989            const RawAbsoluteAxisInfo& axis, const char* name);
990};
991
992
993class SwitchInputMapper : public InputMapper {
994public:
995    SwitchInputMapper(InputDevice* device);
996    virtual ~SwitchInputMapper();
997
998    virtual uint32_t getSources();
999    virtual void process(const RawEvent* rawEvent);
1000
1001    virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
1002
1003private:
1004    uint32_t mUpdatedSwitchValues;
1005    uint32_t mUpdatedSwitchMask;
1006
1007    void processSwitch(int32_t switchCode, int32_t switchValue);
1008    void sync(nsecs_t when);
1009};
1010
1011
1012class VibratorInputMapper : public InputMapper {
1013public:
1014    VibratorInputMapper(InputDevice* device);
1015    virtual ~VibratorInputMapper();
1016
1017    virtual uint32_t getSources();
1018    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1019    virtual void process(const RawEvent* rawEvent);
1020
1021    virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1022            int32_t token);
1023    virtual void cancelVibrate(int32_t token);
1024    virtual void timeoutExpired(nsecs_t when);
1025    virtual void dump(String8& dump);
1026
1027private:
1028    bool mVibrating;
1029    nsecs_t mPattern[MAX_VIBRATE_PATTERN_SIZE];
1030    size_t mPatternSize;
1031    ssize_t mRepeat;
1032    int32_t mToken;
1033    ssize_t mIndex;
1034    nsecs_t mNextStepTime;
1035
1036    void nextStep();
1037    void stopVibrating();
1038};
1039
1040
1041class KeyboardInputMapper : public InputMapper {
1042public:
1043    KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType);
1044    virtual ~KeyboardInputMapper();
1045
1046    virtual uint32_t getSources();
1047    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1048    virtual void dump(String8& dump);
1049    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1050    virtual void reset(nsecs_t when);
1051    virtual void process(const RawEvent* rawEvent);
1052
1053    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1054    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1055    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1056            const int32_t* keyCodes, uint8_t* outFlags);
1057
1058    virtual int32_t getMetaState();
1059
1060private:
1061    struct KeyDown {
1062        int32_t keyCode;
1063        int32_t scanCode;
1064    };
1065
1066    uint32_t mSource;
1067    int32_t mKeyboardType;
1068
1069    int32_t mOrientation; // orientation for dpad keys
1070
1071    Vector<KeyDown> mKeyDowns; // keys that are down
1072    int32_t mMetaState;
1073    nsecs_t mDownTime; // time of most recent key down
1074
1075    int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none
1076
1077    struct LedState {
1078        bool avail; // led is available
1079        bool on;    // we think the led is currently on
1080    };
1081    LedState mCapsLockLedState;
1082    LedState mNumLockLedState;
1083    LedState mScrollLockLedState;
1084
1085    // Immutable configuration parameters.
1086    struct Parameters {
1087        bool hasAssociatedDisplay;
1088        bool orientationAware;
1089    } mParameters;
1090
1091    void configureParameters();
1092    void dumpParameters(String8& dump);
1093
1094    bool isKeyboardOrGamepadKey(int32_t scanCode);
1095
1096    void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
1097            uint32_t policyFlags);
1098
1099    ssize_t findKeyDown(int32_t scanCode);
1100
1101    void resetLedState();
1102    void initializeLedState(LedState& ledState, int32_t led);
1103    void updateLedState(bool reset);
1104    void updateLedStateForModifier(LedState& ledState, int32_t led,
1105            int32_t modifier, bool reset);
1106};
1107
1108
1109class CursorInputMapper : public InputMapper {
1110public:
1111    CursorInputMapper(InputDevice* device);
1112    virtual ~CursorInputMapper();
1113
1114    virtual uint32_t getSources();
1115    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1116    virtual void dump(String8& dump);
1117    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1118    virtual void reset(nsecs_t when);
1119    virtual void process(const RawEvent* rawEvent);
1120
1121    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1122
1123    virtual void fadePointer();
1124
1125private:
1126    // Amount that trackball needs to move in order to generate a key event.
1127    static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
1128
1129    // Immutable configuration parameters.
1130    struct Parameters {
1131        enum Mode {
1132            MODE_POINTER,
1133            MODE_NAVIGATION,
1134        };
1135
1136        Mode mode;
1137        bool hasAssociatedDisplay;
1138        bool orientationAware;
1139    } mParameters;
1140
1141    CursorButtonAccumulator mCursorButtonAccumulator;
1142    CursorMotionAccumulator mCursorMotionAccumulator;
1143    CursorScrollAccumulator mCursorScrollAccumulator;
1144
1145    int32_t mSource;
1146    float mXScale;
1147    float mYScale;
1148    float mXPrecision;
1149    float mYPrecision;
1150
1151    float mVWheelScale;
1152    float mHWheelScale;
1153
1154    // Velocity controls for mouse pointer and wheel movements.
1155    // The controls for X and Y wheel movements are separate to keep them decoupled.
1156    VelocityControl mPointerVelocityControl;
1157    VelocityControl mWheelXVelocityControl;
1158    VelocityControl mWheelYVelocityControl;
1159
1160    int32_t mOrientation;
1161
1162    sp<PointerControllerInterface> mPointerController;
1163
1164    int32_t mButtonState;
1165    nsecs_t mDownTime;
1166
1167    void configureParameters();
1168    void dumpParameters(String8& dump);
1169
1170    void sync(nsecs_t when);
1171};
1172
1173
1174class TouchInputMapper : public InputMapper {
1175public:
1176    TouchInputMapper(InputDevice* device);
1177    virtual ~TouchInputMapper();
1178
1179    virtual uint32_t getSources();
1180    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1181    virtual void dump(String8& dump);
1182    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1183    virtual void reset(nsecs_t when);
1184    virtual void process(const RawEvent* rawEvent);
1185
1186    virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1187    virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1188    virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1189            const int32_t* keyCodes, uint8_t* outFlags);
1190
1191    virtual void fadePointer();
1192    virtual void timeoutExpired(nsecs_t when);
1193
1194protected:
1195    CursorButtonAccumulator mCursorButtonAccumulator;
1196    CursorScrollAccumulator mCursorScrollAccumulator;
1197    TouchButtonAccumulator mTouchButtonAccumulator;
1198
1199    struct VirtualKey {
1200        int32_t keyCode;
1201        int32_t scanCode;
1202        uint32_t flags;
1203
1204        // computed hit box, specified in touch screen coords based on known display size
1205        int32_t hitLeft;
1206        int32_t hitTop;
1207        int32_t hitRight;
1208        int32_t hitBottom;
1209
1210        inline bool isHit(int32_t x, int32_t y) const {
1211            return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
1212        }
1213    };
1214
1215    // Input sources and device mode.
1216    uint32_t mSource;
1217
1218    enum DeviceMode {
1219        DEVICE_MODE_DISABLED, // input is disabled
1220        DEVICE_MODE_DIRECT, // direct mapping (touchscreen)
1221        DEVICE_MODE_UNSCALED, // unscaled mapping (touchpad)
1222        DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
1223        DEVICE_MODE_POINTER, // pointer mapping (pointer)
1224    };
1225    DeviceMode mDeviceMode;
1226
1227    // The reader's configuration.
1228    InputReaderConfiguration mConfig;
1229
1230    // Immutable configuration parameters.
1231    struct Parameters {
1232        enum DeviceType {
1233            DEVICE_TYPE_TOUCH_SCREEN,
1234            DEVICE_TYPE_TOUCH_PAD,
1235            DEVICE_TYPE_TOUCH_NAVIGATION,
1236            DEVICE_TYPE_POINTER,
1237        };
1238
1239        DeviceType deviceType;
1240        bool hasAssociatedDisplay;
1241        bool associatedDisplayIsExternal;
1242        bool orientationAware;
1243        bool hasButtonUnderPad;
1244
1245        enum GestureMode {
1246            GESTURE_MODE_POINTER,
1247            GESTURE_MODE_SPOTS,
1248        };
1249        GestureMode gestureMode;
1250
1251        bool wake;
1252    } mParameters;
1253
1254    // Immutable calibration parameters in parsed form.
1255    struct Calibration {
1256        // Size
1257        enum SizeCalibration {
1258            SIZE_CALIBRATION_DEFAULT,
1259            SIZE_CALIBRATION_NONE,
1260            SIZE_CALIBRATION_GEOMETRIC,
1261            SIZE_CALIBRATION_DIAMETER,
1262            SIZE_CALIBRATION_BOX,
1263            SIZE_CALIBRATION_AREA,
1264        };
1265
1266        SizeCalibration sizeCalibration;
1267
1268        bool haveSizeScale;
1269        float sizeScale;
1270        bool haveSizeBias;
1271        float sizeBias;
1272        bool haveSizeIsSummed;
1273        bool sizeIsSummed;
1274
1275        // Pressure
1276        enum PressureCalibration {
1277            PRESSURE_CALIBRATION_DEFAULT,
1278            PRESSURE_CALIBRATION_NONE,
1279            PRESSURE_CALIBRATION_PHYSICAL,
1280            PRESSURE_CALIBRATION_AMPLITUDE,
1281        };
1282
1283        PressureCalibration pressureCalibration;
1284        bool havePressureScale;
1285        float pressureScale;
1286
1287        // Orientation
1288        enum OrientationCalibration {
1289            ORIENTATION_CALIBRATION_DEFAULT,
1290            ORIENTATION_CALIBRATION_NONE,
1291            ORIENTATION_CALIBRATION_INTERPOLATED,
1292            ORIENTATION_CALIBRATION_VECTOR,
1293        };
1294
1295        OrientationCalibration orientationCalibration;
1296
1297        // Distance
1298        enum DistanceCalibration {
1299            DISTANCE_CALIBRATION_DEFAULT,
1300            DISTANCE_CALIBRATION_NONE,
1301            DISTANCE_CALIBRATION_SCALED,
1302        };
1303
1304        DistanceCalibration distanceCalibration;
1305        bool haveDistanceScale;
1306        float distanceScale;
1307
1308        enum CoverageCalibration {
1309            COVERAGE_CALIBRATION_DEFAULT,
1310            COVERAGE_CALIBRATION_NONE,
1311            COVERAGE_CALIBRATION_BOX,
1312        };
1313
1314        CoverageCalibration coverageCalibration;
1315
1316        inline void applySizeScaleAndBias(float* outSize) const {
1317            if (haveSizeScale) {
1318                *outSize *= sizeScale;
1319            }
1320            if (haveSizeBias) {
1321                *outSize += sizeBias;
1322            }
1323            if (*outSize < 0) {
1324                *outSize = 0;
1325            }
1326        }
1327    } mCalibration;
1328
1329    // Affine location transformation/calibration
1330    struct TouchAffineTransformation mAffineTransform;
1331
1332    // Raw pointer axis information from the driver.
1333    RawPointerAxes mRawPointerAxes;
1334
1335    // Raw pointer sample data.
1336    RawPointerData mCurrentRawPointerData;
1337    RawPointerData mLastRawPointerData;
1338
1339    // Cooked pointer sample data.
1340    CookedPointerData mCurrentCookedPointerData;
1341    CookedPointerData mLastCookedPointerData;
1342
1343    // Button state.
1344    int32_t mCurrentButtonState;
1345    int32_t mLastButtonState;
1346
1347    // Scroll state.
1348    int32_t mCurrentRawVScroll;
1349    int32_t mCurrentRawHScroll;
1350
1351    // Id bits used to differentiate fingers, stylus and mouse tools.
1352    BitSet32 mCurrentFingerIdBits; // finger or unknown
1353    BitSet32 mLastFingerIdBits;
1354    BitSet32 mCurrentStylusIdBits; // stylus or eraser
1355    BitSet32 mLastStylusIdBits;
1356    BitSet32 mCurrentMouseIdBits; // mouse or lens
1357    BitSet32 mLastMouseIdBits;
1358
1359    // True if we sent a HOVER_ENTER event.
1360    bool mSentHoverEnter;
1361
1362    // The time the primary pointer last went down.
1363    nsecs_t mDownTime;
1364
1365    // The pointer controller, or null if the device is not a pointer.
1366    sp<PointerControllerInterface> mPointerController;
1367
1368    Vector<VirtualKey> mVirtualKeys;
1369
1370    virtual void configureParameters();
1371    virtual void dumpParameters(String8& dump);
1372    virtual void configureRawPointerAxes();
1373    virtual void dumpRawPointerAxes(String8& dump);
1374    virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
1375    virtual void dumpSurface(String8& dump);
1376    virtual void configureVirtualKeys();
1377    virtual void dumpVirtualKeys(String8& dump);
1378    virtual void parseCalibration();
1379    virtual void resolveCalibration();
1380    virtual void dumpCalibration(String8& dump);
1381    virtual void dumpAffineTransformation(String8& dump);
1382    virtual bool hasStylus() const = 0;
1383    virtual void updateAffineTransformation();
1384
1385    virtual void syncTouch(nsecs_t when, bool* outHavePointerIds) = 0;
1386
1387private:
1388    // The current viewport.
1389    // The components of the viewport are specified in the display's rotated orientation.
1390    DisplayViewport mViewport;
1391
1392    // The surface orientation, width and height set by configureSurface().
1393    // The width and height are derived from the viewport but are specified
1394    // in the natural orientation.
1395    // The surface origin specifies how the surface coordinates should be translated
1396    // to align with the logical display coordinate space.
1397    // The orientation may be different from the viewport orientation as it specifies
1398    // the rotation of the surface coordinates required to produce the viewport's
1399    // requested orientation, so it will depend on whether the device is orientation aware.
1400    int32_t mSurfaceWidth;
1401    int32_t mSurfaceHeight;
1402    int32_t mSurfaceLeft;
1403    int32_t mSurfaceTop;
1404    int32_t mSurfaceOrientation;
1405
1406    // Translation and scaling factors, orientation-independent.
1407    float mXTranslate;
1408    float mXScale;
1409    float mXPrecision;
1410
1411    float mYTranslate;
1412    float mYScale;
1413    float mYPrecision;
1414
1415    float mGeometricScale;
1416
1417    float mPressureScale;
1418
1419    float mSizeScale;
1420
1421    float mOrientationScale;
1422
1423    float mDistanceScale;
1424
1425    bool mHaveTilt;
1426    float mTiltXCenter;
1427    float mTiltXScale;
1428    float mTiltYCenter;
1429    float mTiltYScale;
1430
1431    // Oriented motion ranges for input device info.
1432    struct OrientedRanges {
1433        InputDeviceInfo::MotionRange x;
1434        InputDeviceInfo::MotionRange y;
1435        InputDeviceInfo::MotionRange pressure;
1436
1437        bool haveSize;
1438        InputDeviceInfo::MotionRange size;
1439
1440        bool haveTouchSize;
1441        InputDeviceInfo::MotionRange touchMajor;
1442        InputDeviceInfo::MotionRange touchMinor;
1443
1444        bool haveToolSize;
1445        InputDeviceInfo::MotionRange toolMajor;
1446        InputDeviceInfo::MotionRange toolMinor;
1447
1448        bool haveOrientation;
1449        InputDeviceInfo::MotionRange orientation;
1450
1451        bool haveDistance;
1452        InputDeviceInfo::MotionRange distance;
1453
1454        bool haveTilt;
1455        InputDeviceInfo::MotionRange tilt;
1456
1457        OrientedRanges() {
1458            clear();
1459        }
1460
1461        void clear() {
1462            haveSize = false;
1463            haveTouchSize = false;
1464            haveToolSize = false;
1465            haveOrientation = false;
1466            haveDistance = false;
1467            haveTilt = false;
1468        }
1469    } mOrientedRanges;
1470
1471    // Oriented dimensions and precision.
1472    float mOrientedXPrecision;
1473    float mOrientedYPrecision;
1474
1475    struct CurrentVirtualKeyState {
1476        bool down;
1477        bool ignored;
1478        nsecs_t downTime;
1479        int32_t keyCode;
1480        int32_t scanCode;
1481    } mCurrentVirtualKey;
1482
1483    // Scale factor for gesture or mouse based pointer movements.
1484    float mPointerXMovementScale;
1485    float mPointerYMovementScale;
1486
1487    // Scale factor for gesture based zooming and other freeform motions.
1488    float mPointerXZoomScale;
1489    float mPointerYZoomScale;
1490
1491    // The maximum swipe width.
1492    float mPointerGestureMaxSwipeWidth;
1493
1494    struct PointerDistanceHeapElement {
1495        uint32_t currentPointerIndex : 8;
1496        uint32_t lastPointerIndex : 8;
1497        uint64_t distance : 48; // squared distance
1498    };
1499
1500    enum PointerUsage {
1501        POINTER_USAGE_NONE,
1502        POINTER_USAGE_GESTURES,
1503        POINTER_USAGE_STYLUS,
1504        POINTER_USAGE_MOUSE,
1505    };
1506    PointerUsage mPointerUsage;
1507
1508    struct PointerGesture {
1509        enum Mode {
1510            // No fingers, button is not pressed.
1511            // Nothing happening.
1512            NEUTRAL,
1513
1514            // No fingers, button is not pressed.
1515            // Tap detected.
1516            // Emits DOWN and UP events at the pointer location.
1517            TAP,
1518
1519            // Exactly one finger dragging following a tap.
1520            // Pointer follows the active finger.
1521            // Emits DOWN, MOVE and UP events at the pointer location.
1522            //
1523            // Detect double-taps when the finger goes up while in TAP_DRAG mode.
1524            TAP_DRAG,
1525
1526            // Button is pressed.
1527            // Pointer follows the active finger if there is one.  Other fingers are ignored.
1528            // Emits DOWN, MOVE and UP events at the pointer location.
1529            BUTTON_CLICK_OR_DRAG,
1530
1531            // Exactly one finger, button is not pressed.
1532            // Pointer follows the active finger.
1533            // Emits HOVER_MOVE events at the pointer location.
1534            //
1535            // Detect taps when the finger goes up while in HOVER mode.
1536            HOVER,
1537
1538            // Exactly two fingers but neither have moved enough to clearly indicate
1539            // whether a swipe or freeform gesture was intended.  We consider the
1540            // pointer to be pressed so this enables clicking or long-pressing on buttons.
1541            // Pointer does not move.
1542            // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
1543            PRESS,
1544
1545            // Exactly two fingers moving in the same direction, button is not pressed.
1546            // Pointer does not move.
1547            // Emits DOWN, MOVE and UP events with a single pointer coordinate that
1548            // follows the midpoint between both fingers.
1549            SWIPE,
1550
1551            // Two or more fingers moving in arbitrary directions, button is not pressed.
1552            // Pointer does not move.
1553            // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
1554            // each finger individually relative to the initial centroid of the finger.
1555            FREEFORM,
1556
1557            // Waiting for quiet time to end before starting the next gesture.
1558            QUIET,
1559        };
1560
1561        // Time the first finger went down.
1562        nsecs_t firstTouchTime;
1563
1564        // The active pointer id from the raw touch data.
1565        int32_t activeTouchId; // -1 if none
1566
1567        // The active pointer id from the gesture last delivered to the application.
1568        int32_t activeGestureId; // -1 if none
1569
1570        // Pointer coords and ids for the current and previous pointer gesture.
1571        Mode currentGestureMode;
1572        BitSet32 currentGestureIdBits;
1573        uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
1574        PointerProperties currentGestureProperties[MAX_POINTERS];
1575        PointerCoords currentGestureCoords[MAX_POINTERS];
1576
1577        Mode lastGestureMode;
1578        BitSet32 lastGestureIdBits;
1579        uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
1580        PointerProperties lastGestureProperties[MAX_POINTERS];
1581        PointerCoords lastGestureCoords[MAX_POINTERS];
1582
1583        // Time the pointer gesture last went down.
1584        nsecs_t downTime;
1585
1586        // Time when the pointer went down for a TAP.
1587        nsecs_t tapDownTime;
1588
1589        // Time when the pointer went up for a TAP.
1590        nsecs_t tapUpTime;
1591
1592        // Location of initial tap.
1593        float tapX, tapY;
1594
1595        // Time we started waiting for quiescence.
1596        nsecs_t quietTime;
1597
1598        // Reference points for multitouch gestures.
1599        float referenceTouchX;    // reference touch X/Y coordinates in surface units
1600        float referenceTouchY;
1601        float referenceGestureX;  // reference gesture X/Y coordinates in pixels
1602        float referenceGestureY;
1603
1604        // Distance that each pointer has traveled which has not yet been
1605        // subsumed into the reference gesture position.
1606        BitSet32 referenceIdBits;
1607        struct Delta {
1608            float dx, dy;
1609        };
1610        Delta referenceDeltas[MAX_POINTER_ID + 1];
1611
1612        // Describes how touch ids are mapped to gesture ids for freeform gestures.
1613        uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
1614
1615        // A velocity tracker for determining whether to switch active pointers during drags.
1616        VelocityTracker velocityTracker;
1617
1618        void reset() {
1619            firstTouchTime = LLONG_MIN;
1620            activeTouchId = -1;
1621            activeGestureId = -1;
1622            currentGestureMode = NEUTRAL;
1623            currentGestureIdBits.clear();
1624            lastGestureMode = NEUTRAL;
1625            lastGestureIdBits.clear();
1626            downTime = 0;
1627            velocityTracker.clear();
1628            resetTap();
1629            resetQuietTime();
1630        }
1631
1632        void resetTap() {
1633            tapDownTime = LLONG_MIN;
1634            tapUpTime = LLONG_MIN;
1635        }
1636
1637        void resetQuietTime() {
1638            quietTime = LLONG_MIN;
1639        }
1640    } mPointerGesture;
1641
1642    struct PointerSimple {
1643        PointerCoords currentCoords;
1644        PointerProperties currentProperties;
1645        PointerCoords lastCoords;
1646        PointerProperties lastProperties;
1647
1648        // True if the pointer is down.
1649        bool down;
1650
1651        // True if the pointer is hovering.
1652        bool hovering;
1653
1654        // Time the pointer last went down.
1655        nsecs_t downTime;
1656
1657        void reset() {
1658            currentCoords.clear();
1659            currentProperties.clear();
1660            lastCoords.clear();
1661            lastProperties.clear();
1662            down = false;
1663            hovering = false;
1664            downTime = 0;
1665        }
1666    } mPointerSimple;
1667
1668    // The pointer and scroll velocity controls.
1669    VelocityControl mPointerVelocityControl;
1670    VelocityControl mWheelXVelocityControl;
1671    VelocityControl mWheelYVelocityControl;
1672
1673    void sync(nsecs_t when);
1674
1675    bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
1676    void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1677            int32_t keyEventAction, int32_t keyEventFlags);
1678
1679    void dispatchTouches(nsecs_t when, uint32_t policyFlags);
1680    void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
1681    void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
1682    void cookPointerData();
1683
1684    void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
1685    void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
1686
1687    void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
1688    void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
1689    bool preparePointerGestures(nsecs_t when,
1690            bool* outCancelPreviousGesture, bool* outFinishPreviousGesture,
1691            bool isTimeout);
1692
1693    void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
1694    void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
1695
1696    void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
1697    void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
1698
1699    void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
1700            bool down, bool hovering);
1701    void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
1702
1703    // Dispatches a motion event.
1704    // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
1705    // method will take care of setting the index and transmuting the action to DOWN or UP
1706    // it is the first / last pointer to go down / up.
1707    void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
1708            int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
1709            int32_t edgeFlags,
1710            const PointerProperties* properties, const PointerCoords* coords,
1711            const uint32_t* idToIndex, BitSet32 idBits,
1712            int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
1713
1714    // Updates pointer coords and properties for pointers with specified ids that have moved.
1715    // Returns true if any of them changed.
1716    bool updateMovedPointers(const PointerProperties* inProperties,
1717            const PointerCoords* inCoords, const uint32_t* inIdToIndex,
1718            PointerProperties* outProperties, PointerCoords* outCoords,
1719            const uint32_t* outIdToIndex, BitSet32 idBits) const;
1720
1721    bool isPointInsideSurface(int32_t x, int32_t y);
1722    const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
1723
1724    void assignPointerIds();
1725};
1726
1727
1728class SingleTouchInputMapper : public TouchInputMapper {
1729public:
1730    SingleTouchInputMapper(InputDevice* device);
1731    virtual ~SingleTouchInputMapper();
1732
1733    virtual void reset(nsecs_t when);
1734    virtual void process(const RawEvent* rawEvent);
1735
1736protected:
1737    virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1738    virtual void configureRawPointerAxes();
1739    virtual bool hasStylus() const;
1740
1741private:
1742    SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
1743};
1744
1745
1746class MultiTouchInputMapper : public TouchInputMapper {
1747public:
1748    MultiTouchInputMapper(InputDevice* device);
1749    virtual ~MultiTouchInputMapper();
1750
1751    virtual void reset(nsecs_t when);
1752    virtual void process(const RawEvent* rawEvent);
1753
1754protected:
1755    virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1756    virtual void configureRawPointerAxes();
1757    virtual bool hasStylus() const;
1758
1759private:
1760    MultiTouchMotionAccumulator mMultiTouchMotionAccumulator;
1761
1762    // Specifies the pointer id bits that are in use, and their associated tracking id.
1763    BitSet32 mPointerIdBits;
1764    int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1];
1765};
1766
1767
1768class JoystickInputMapper : public InputMapper {
1769public:
1770    JoystickInputMapper(InputDevice* device);
1771    virtual ~JoystickInputMapper();
1772
1773    virtual uint32_t getSources();
1774    virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1775    virtual void dump(String8& dump);
1776    virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1777    virtual void reset(nsecs_t when);
1778    virtual void process(const RawEvent* rawEvent);
1779
1780private:
1781    struct Axis {
1782        RawAbsoluteAxisInfo rawAxisInfo;
1783        AxisInfo axisInfo;
1784
1785        bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1786
1787        float scale;   // scale factor from raw to normalized values
1788        float offset;  // offset to add after scaling for normalization
1789        float highScale;  // scale factor from raw to normalized values of high split
1790        float highOffset; // offset to add after scaling for normalization of high split
1791
1792        float min;        // normalized inclusive minimum
1793        float max;        // normalized inclusive maximum
1794        float flat;       // normalized flat region size
1795        float fuzz;       // normalized error tolerance
1796        float resolution; // normalized resolution in units/mm
1797
1798        float filter;  // filter out small variations of this size
1799        float currentValue; // current value
1800        float newValue; // most recent value
1801        float highCurrentValue; // current value of high split
1802        float highNewValue; // most recent value of high split
1803
1804        void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
1805                bool explicitlyMapped, float scale, float offset,
1806                float highScale, float highOffset,
1807                float min, float max, float flat, float fuzz, float resolution) {
1808            this->rawAxisInfo = rawAxisInfo;
1809            this->axisInfo = axisInfo;
1810            this->explicitlyMapped = explicitlyMapped;
1811            this->scale = scale;
1812            this->offset = offset;
1813            this->highScale = highScale;
1814            this->highOffset = highOffset;
1815            this->min = min;
1816            this->max = max;
1817            this->flat = flat;
1818            this->fuzz = fuzz;
1819            this->resolution = resolution;
1820            this->filter = 0;
1821            resetValue();
1822        }
1823
1824        void resetValue() {
1825            this->currentValue = 0;
1826            this->newValue = 0;
1827            this->highCurrentValue = 0;
1828            this->highNewValue = 0;
1829        }
1830    };
1831
1832    // Axes indexed by raw ABS_* axis index.
1833    KeyedVector<int32_t, Axis> mAxes;
1834
1835    void sync(nsecs_t when, bool force);
1836
1837    bool haveAxis(int32_t axisId);
1838    void pruneAxes(bool ignoreExplicitlyMappedAxes);
1839    bool filterAxes(bool force);
1840
1841    static bool hasValueChangedSignificantly(float filter,
1842            float newValue, float currentValue, float min, float max);
1843    static bool hasMovedNearerToValueWithinFilteredRange(float filter,
1844            float newValue, float currentValue, float thresholdValue);
1845
1846    static bool isCenteredAxis(int32_t axis);
1847    static int32_t getCompatAxis(int32_t axis);
1848
1849    static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info);
1850    static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
1851            float value);
1852};
1853
1854} // namespace android
1855
1856#endif // _UI_INPUT_READER_H
1857