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