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