2 * Copyright (C) 2010 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #ifndef _UI_INPUT_READER_H
18 #define _UI_INPUT_READER_H
21 #include "PointerControllerInterface.h"
22 #include "InputListener.h"
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/Condition.h>
31 #include <utils/Thread.h>
32 #include <utils/Mutex.h>
33 #include <utils/Timers.h>
34 #include <utils/RefBase.h>
35 #include <utils/String8.h>
36 #include <utils/BitSet.h>
37 #include <utils/SortedVector.h>
42 // Maximum supported size of a vibration pattern.
43 // Must be at least 2.
44 #define MAX_VIBRATE_PATTERN_SIZE 100
46 // Maximum allowable delay value in a vibration pattern before
47 // which the delay will be truncated.
48 #define MAX_VIBRATE_PATTERN_DELAY_NSECS (1000000 * 1000000000LL)
56 * Input reader configuration.
58 * Specifies various options that modify the behavior of the input reader.
60 struct InputReaderConfiguration {
61 // Describes changes that have occurred.
63 // The pointer speed changed.
64 CHANGE_POINTER_SPEED = 1 << 0,
66 // The pointer gesture control changed.
67 CHANGE_POINTER_GESTURE_ENABLEMENT = 1 << 1,
69 // The display size or orientation changed.
70 CHANGE_DISPLAY_INFO = 1 << 2,
72 // The visible touches option changed.
73 CHANGE_SHOW_TOUCHES = 1 << 3,
75 // The keyboard layouts must be reloaded.
76 CHANGE_KEYBOARD_LAYOUTS = 1 << 4,
78 // The device name alias supplied by the may have changed for some devices.
79 CHANGE_DEVICE_ALIAS = 1 << 5,
81 // The location calibration matrix changed.
82 CHANGE_TOUCH_AFFINE_TRANSFORMATION = 1 << 6,
84 // The presence of an external stylus has changed.
85 CHANGE_EXTERNAL_STYLUS_PRESENCE = 1 << 7,
87 // The pointer capture mode has changed.
88 CHANGE_POINTER_CAPTURE = 1 << 8,
90 // The set of disabled input devices (disabledDevices) has changed.
91 CHANGE_ENABLED_STATE = 1 << 9,
93 // All devices must be reopened.
94 CHANGE_MUST_REOPEN = 1 << 31,
97 // Gets the amount of time to disable virtual keys after the screen is touched
98 // in order to filter out accidental virtual key presses due to swiping gestures
99 // or taps near the edge of the display. May be 0 to disable the feature.
100 nsecs_t virtualKeyQuietTime;
102 // The excluded device names for the platform.
103 // Devices with these names will be ignored.
104 Vector<String8> excludedDeviceNames;
106 // Velocity control parameters for mouse pointer movements.
107 VelocityControlParameters pointerVelocityControlParameters;
109 // Velocity control parameters for mouse wheel movements.
110 VelocityControlParameters wheelVelocityControlParameters;
112 // True if pointer gestures are enabled.
113 bool pointerGesturesEnabled;
115 // Quiet time between certain pointer gesture transitions.
116 // Time to allow for all fingers or buttons to settle into a stable state before
117 // starting a new gesture.
118 nsecs_t pointerGestureQuietInterval;
120 // The minimum speed that a pointer must travel for us to consider switching the active
121 // touch pointer to it during a drag. This threshold is set to avoid switching due
122 // to noise from a finger resting on the touch pad (perhaps just pressing it down).
123 float pointerGestureDragMinSwitchSpeed; // in pixels per second
125 // Tap gesture delay time.
126 // The time between down and up must be less than this to be considered a tap.
127 nsecs_t pointerGestureTapInterval;
129 // Tap drag gesture delay time.
130 // The time between the previous tap's up and the next down must be less than
131 // this to be considered a drag. Otherwise, the previous tap is finished and a
134 // Note that the previous tap will be held down for this entire duration so this
135 // interval must be shorter than the long press timeout.
136 nsecs_t pointerGestureTapDragInterval;
138 // The distance in pixels that the pointer is allowed to move from initial down
139 // to up and still be called a tap.
140 float pointerGestureTapSlop; // in pixels
142 // Time after the first touch points go down to settle on an initial centroid.
143 // This is intended to be enough time to handle cases where the user puts down two
144 // fingers at almost but not quite exactly the same time.
145 nsecs_t pointerGestureMultitouchSettleInterval;
147 // The transition from PRESS to SWIPE or FREEFORM gesture mode is made when
148 // at least two pointers have moved at least this far from their starting place.
149 float pointerGestureMultitouchMinDistance; // in pixels
151 // The transition from PRESS to SWIPE gesture mode can only occur when the
152 // cosine of the angle between the two vectors is greater than or equal to than this value
153 // which indicates that the vectors are oriented in the same direction.
154 // When the vectors are oriented in the exactly same direction, the cosine is 1.0.
155 // (In exactly opposite directions, the cosine is -1.0.)
156 float pointerGestureSwipeTransitionAngleCosine;
158 // The transition from PRESS to SWIPE gesture mode can only occur when the
159 // fingers are no more than this far apart relative to the diagonal size of
160 // the touch pad. For example, a ratio of 0.5 means that the fingers must be
161 // no more than half the diagonal size of the touch pad apart.
162 float pointerGestureSwipeMaxWidthRatio;
164 // The gesture movement speed factor relative to the size of the display.
165 // Movement speed applies when the fingers are moving in the same direction.
166 // Without acceleration, a full swipe of the touch pad diagonal in movement mode
167 // will cover this portion of the display diagonal.
168 float pointerGestureMovementSpeedRatio;
170 // The gesture zoom speed factor relative to the size of the display.
171 // Zoom speed applies when the fingers are mostly moving relative to each other
172 // to execute a scale gesture or similar.
173 // Without acceleration, a full swipe of the touch pad diagonal in zoom mode
174 // will cover this portion of the display diagonal.
175 float pointerGestureZoomSpeedRatio;
177 // True to show the location of touches on the touch screen as spots.
180 // True if pointer capture is enabled.
183 // The set of currently disabled input devices.
184 SortedVector<int32_t> disabledDevices;
186 InputReaderConfiguration() :
187 virtualKeyQuietTime(0),
188 pointerVelocityControlParameters(1.0f, 500.0f, 3000.0f, 3.0f),
189 wheelVelocityControlParameters(1.0f, 15.0f, 50.0f, 4.0f),
190 pointerGesturesEnabled(true),
191 pointerGestureQuietInterval(100 * 1000000LL), // 100 ms
192 pointerGestureDragMinSwitchSpeed(50), // 50 pixels per second
193 pointerGestureTapInterval(150 * 1000000LL), // 150 ms
194 pointerGestureTapDragInterval(150 * 1000000LL), // 150 ms
195 pointerGestureTapSlop(10.0f), // 10 pixels
196 pointerGestureMultitouchSettleInterval(100 * 1000000LL), // 100 ms
197 pointerGestureMultitouchMinDistance(15), // 15 pixels
198 pointerGestureSwipeTransitionAngleCosine(0.2588f), // cosine of 75 degrees
199 pointerGestureSwipeMaxWidthRatio(0.25f),
200 pointerGestureMovementSpeedRatio(0.8f),
201 pointerGestureZoomSpeedRatio(0.3f),
202 showTouches(false) { }
204 bool getDisplayViewport(ViewportType viewportType, const String8* displayId,
205 DisplayViewport* outViewport) const;
206 void setPhysicalDisplayViewport(ViewportType viewportType, const DisplayViewport& viewport);
207 void setVirtualDisplayViewports(const Vector<DisplayViewport>& viewports);
210 void dump(String8& dump) const;
211 void dumpViewport(String8& dump, const DisplayViewport& viewport) const;
214 DisplayViewport mInternalDisplay;
215 DisplayViewport mExternalDisplay;
216 Vector<DisplayViewport> mVirtualDisplays;
220 struct TouchAffineTransformation {
228 TouchAffineTransformation() :
229 x_scale(1.0f), x_ymix(0.0f), x_offset(0.0f),
230 y_xmix(0.0f), y_scale(1.0f), y_offset(0.0f) {
233 TouchAffineTransformation(float xscale, float xymix, float xoffset,
234 float yxmix, float yscale, float yoffset) :
235 x_scale(xscale), x_ymix(xymix), x_offset(xoffset),
236 y_xmix(yxmix), y_scale(yscale), y_offset(yoffset) {
239 void applyTo(float& x, float& y) const;
244 * Input reader policy interface.
246 * The input reader policy is used by the input reader to interact with the Window Manager
247 * and other system components.
249 * The actual implementation is partially supported by callbacks into the DVM
250 * via JNI. This interface is also mocked in the unit tests.
252 * These methods must NOT re-enter the input reader since they may be called while
253 * holding the input reader lock.
255 class InputReaderPolicyInterface : public virtual RefBase {
257 InputReaderPolicyInterface() { }
258 virtual ~InputReaderPolicyInterface() { }
261 /* Gets the input reader configuration. */
262 virtual void getReaderConfiguration(InputReaderConfiguration* outConfig) = 0;
264 /* Gets a pointer controller associated with the specified cursor device (ie. a mouse). */
265 virtual sp<PointerControllerInterface> obtainPointerController(int32_t deviceId) = 0;
267 /* Notifies the input reader policy that some input devices have changed
268 * and provides information about all current input devices.
270 virtual void notifyInputDevicesChanged(const Vector<InputDeviceInfo>& inputDevices) = 0;
272 /* Gets the keyboard layout for a particular input device. */
273 virtual sp<KeyCharacterMap> getKeyboardLayoutOverlay(
274 const InputDeviceIdentifier& identifier) = 0;
276 /* Gets a user-supplied alias for a particular input device, or an empty string if none. */
277 virtual String8 getDeviceAlias(const InputDeviceIdentifier& identifier) = 0;
279 /* Gets the affine calibration associated with the specified device. */
280 virtual TouchAffineTransformation getTouchAffineTransformation(
281 const String8& inputDeviceDescriptor, int32_t surfaceRotation) = 0;
285 /* Processes raw input events and sends cooked event data to an input listener. */
286 class InputReaderInterface : public virtual RefBase {
288 InputReaderInterface() { }
289 virtual ~InputReaderInterface() { }
292 /* Dumps the state of the input reader.
294 * This method may be called on any thread (usually by the input manager). */
295 virtual void dump(String8& dump) = 0;
297 /* Called by the heatbeat to ensures that the reader has not deadlocked. */
298 virtual void monitor() = 0;
300 /* Returns true if the input device is enabled. */
301 virtual bool isInputDeviceEnabled(int32_t deviceId) = 0;
303 /* Runs a single iteration of the processing loop.
304 * Nominally reads and processes one incoming message from the EventHub.
306 * This method should be called on the input reader thread.
308 virtual void loopOnce() = 0;
310 /* Gets information about all input devices.
312 * This method may be called on any thread (usually by the input manager).
314 virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices) = 0;
316 /* Query current input state. */
317 virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
318 int32_t scanCode) = 0;
319 virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
320 int32_t keyCode) = 0;
321 virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
324 /* Toggle Caps Lock */
325 virtual void toggleCapsLockState(int32_t deviceId) = 0;
327 /* Determine whether physical keys exist for the given framework-domain key codes. */
328 virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
329 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) = 0;
331 /* Requests that a reconfiguration of all input devices.
332 * The changes flag is a bitfield that indicates what has changed and whether
333 * the input devices must all be reopened. */
334 virtual void requestRefreshConfiguration(uint32_t changes) = 0;
336 /* Controls the vibrator of a particular input device. */
337 virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
338 ssize_t repeat, int32_t token) = 0;
339 virtual void cancelVibrate(int32_t deviceId, int32_t token) = 0;
343 /* Time the stylus event was received. */
345 /* Pressure as reported by the stylus, normalized to the range [0, 1.0]. */
347 /* The state of the stylus buttons as a bitfield (e.g. AMOTION_EVENT_BUTTON_SECONDARY). */
349 /* Which tool type the stylus is currently using (e.g. AMOTION_EVENT_TOOL_TYPE_ERASER). */
352 void copyFrom(const StylusState& other) {
354 pressure = other.pressure;
355 buttons = other.buttons;
356 toolType = other.toolType;
363 toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
368 /* Internal interface used by individual input devices to access global input device state
369 * and parameters maintained by the input reader.
371 class InputReaderContext {
373 InputReaderContext() { }
374 virtual ~InputReaderContext() { }
376 virtual void updateGlobalMetaState() = 0;
377 virtual int32_t getGlobalMetaState() = 0;
379 virtual void disableVirtualKeysUntil(nsecs_t time) = 0;
380 virtual bool shouldDropVirtualKey(nsecs_t now,
381 InputDevice* device, int32_t keyCode, int32_t scanCode) = 0;
383 virtual void fadePointer() = 0;
385 virtual void requestTimeoutAtTime(nsecs_t when) = 0;
386 virtual int32_t bumpGeneration() = 0;
388 virtual void getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) = 0;
389 virtual void dispatchExternalStylusState(const StylusState& outState) = 0;
391 virtual InputReaderPolicyInterface* getPolicy() = 0;
392 virtual InputListenerInterface* getListener() = 0;
393 virtual EventHubInterface* getEventHub() = 0;
397 /* The input reader reads raw event data from the event hub and processes it into input events
398 * that it sends to the input listener. Some functions of the input reader, such as early
399 * event filtering in low power states, are controlled by a separate policy object.
401 * The InputReader owns a collection of InputMappers. Most of the work it does happens
402 * on the input reader thread but the InputReader can receive queries from other system
403 * components running on arbitrary threads. To keep things manageable, the InputReader
404 * uses a single Mutex to guard its state. The Mutex may be held while calling into the
405 * EventHub or the InputReaderPolicy but it is never held while calling into the
408 class InputReader : public InputReaderInterface {
410 InputReader(const sp<EventHubInterface>& eventHub,
411 const sp<InputReaderPolicyInterface>& policy,
412 const sp<InputListenerInterface>& listener);
413 virtual ~InputReader();
415 virtual void dump(String8& dump);
416 virtual void monitor();
418 virtual void loopOnce();
420 virtual void getInputDevices(Vector<InputDeviceInfo>& outInputDevices);
422 virtual bool isInputDeviceEnabled(int32_t deviceId);
424 virtual int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask,
426 virtual int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
428 virtual int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask,
431 virtual void toggleCapsLockState(int32_t deviceId);
433 virtual bool hasKeys(int32_t deviceId, uint32_t sourceMask,
434 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags);
436 virtual void requestRefreshConfiguration(uint32_t changes);
438 virtual void vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
439 ssize_t repeat, int32_t token);
440 virtual void cancelVibrate(int32_t deviceId, int32_t token);
443 // These members are protected so they can be instrumented by test cases.
444 virtual InputDevice* createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
445 const InputDeviceIdentifier& identifier, uint32_t classes);
447 class ContextImpl : public InputReaderContext {
448 InputReader* mReader;
451 explicit ContextImpl(InputReader* reader);
453 virtual void updateGlobalMetaState();
454 virtual int32_t getGlobalMetaState();
455 virtual void disableVirtualKeysUntil(nsecs_t time);
456 virtual bool shouldDropVirtualKey(nsecs_t now,
457 InputDevice* device, int32_t keyCode, int32_t scanCode);
458 virtual void fadePointer();
459 virtual void requestTimeoutAtTime(nsecs_t when);
460 virtual int32_t bumpGeneration();
461 virtual void getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices);
462 virtual void dispatchExternalStylusState(const StylusState& outState);
463 virtual InputReaderPolicyInterface* getPolicy();
464 virtual InputListenerInterface* getListener();
465 virtual EventHubInterface* getEventHub();
468 friend class ContextImpl;
473 Condition mReaderIsAliveCondition;
475 sp<EventHubInterface> mEventHub;
476 sp<InputReaderPolicyInterface> mPolicy;
477 sp<QueuedInputListener> mQueuedListener;
479 InputReaderConfiguration mConfig;
482 static const int EVENT_BUFFER_SIZE = 256;
483 RawEvent mEventBuffer[EVENT_BUFFER_SIZE];
485 KeyedVector<int32_t, InputDevice*> mDevices;
487 // low-level input event decoding and device management
488 void processEventsLocked(const RawEvent* rawEvents, size_t count);
490 void addDeviceLocked(nsecs_t when, int32_t deviceId);
491 void removeDeviceLocked(nsecs_t when, int32_t deviceId);
492 void processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count);
493 void timeoutExpiredLocked(nsecs_t when);
495 void handleConfigurationChangedLocked(nsecs_t when);
497 int32_t mGlobalMetaState;
498 void updateGlobalMetaStateLocked();
499 int32_t getGlobalMetaStateLocked();
501 void notifyExternalStylusPresenceChanged();
502 void getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices);
503 void dispatchExternalStylusState(const StylusState& state);
505 void fadePointerLocked();
508 int32_t bumpGenerationLocked();
510 void getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices);
512 nsecs_t mDisableVirtualKeysTimeout;
513 void disableVirtualKeysUntilLocked(nsecs_t time);
514 bool shouldDropVirtualKeyLocked(nsecs_t now,
515 InputDevice* device, int32_t keyCode, int32_t scanCode);
517 nsecs_t mNextTimeout;
518 void requestTimeoutAtTimeLocked(nsecs_t when);
520 uint32_t mConfigurationChangesToRefresh;
521 void refreshConfigurationLocked(uint32_t changes);
524 typedef int32_t (InputDevice::*GetStateFunc)(uint32_t sourceMask, int32_t code);
525 int32_t getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
526 GetStateFunc getStateFunc);
527 bool markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
528 const int32_t* keyCodes, uint8_t* outFlags);
532 /* Reads raw events from the event hub and processes them, endlessly. */
533 class InputReaderThread : public Thread {
535 explicit InputReaderThread(const sp<InputReaderInterface>& reader);
536 virtual ~InputReaderThread();
539 sp<InputReaderInterface> mReader;
541 virtual bool threadLoop();
545 /* Represents the state of a single input device. */
548 InputDevice(InputReaderContext* context, int32_t id, int32_t generation, int32_t
549 controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes);
552 inline InputReaderContext* getContext() { return mContext; }
553 inline int32_t getId() const { return mId; }
554 inline int32_t getControllerNumber() const { return mControllerNumber; }
555 inline int32_t getGeneration() const { return mGeneration; }
556 inline const String8& getName() const { return mIdentifier.name; }
557 inline const String8& getDescriptor() { return mIdentifier.descriptor; }
558 inline uint32_t getClasses() const { return mClasses; }
559 inline uint32_t getSources() const { return mSources; }
561 inline bool isExternal() { return mIsExternal; }
562 inline void setExternal(bool external) { mIsExternal = external; }
564 inline void setMic(bool hasMic) { mHasMic = hasMic; }
565 inline bool hasMic() const { return mHasMic; }
567 inline bool isIgnored() { return mMappers.isEmpty(); }
570 void setEnabled(bool enabled, nsecs_t when);
572 void dump(String8& dump);
573 void addMapper(InputMapper* mapper);
574 void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
575 void reset(nsecs_t when);
576 void process(const RawEvent* rawEvents, size_t count);
577 void timeoutExpired(nsecs_t when);
578 void updateExternalStylusState(const StylusState& state);
580 void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
581 int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
582 int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
583 int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
584 bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
585 const int32_t* keyCodes, uint8_t* outFlags);
586 void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token);
587 void cancelVibrate(int32_t token);
588 void cancelTouch(nsecs_t when);
590 int32_t getMetaState();
591 void updateMetaState(int32_t keyCode);
595 void bumpGeneration();
597 void notifyReset(nsecs_t when);
599 inline const PropertyMap& getConfiguration() { return mConfiguration; }
600 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
602 bool hasKey(int32_t code) {
603 return getEventHub()->hasScanCode(mId, code);
606 bool hasAbsoluteAxis(int32_t code) {
607 RawAbsoluteAxisInfo info;
608 getEventHub()->getAbsoluteAxisInfo(mId, code, &info);
612 bool isKeyPressed(int32_t code) {
613 return getEventHub()->getScanCodeState(mId, code) == AKEY_STATE_DOWN;
616 int32_t getAbsoluteAxisValue(int32_t code) {
618 getEventHub()->getAbsoluteAxisValue(mId, code, &value);
623 InputReaderContext* mContext;
626 int32_t mControllerNumber;
627 InputDeviceIdentifier mIdentifier;
631 Vector<InputMapper*> mMappers;
636 bool mDropUntilNextSync;
638 typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
639 int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
641 PropertyMap mConfiguration;
645 /* Keeps track of the state of mouse or touch pad buttons. */
646 class CursorButtonAccumulator {
648 CursorButtonAccumulator();
649 void reset(InputDevice* device);
651 void process(const RawEvent* rawEvent);
653 uint32_t getButtonState() const;
669 /* Keeps track of cursor movements. */
671 class CursorMotionAccumulator {
673 CursorMotionAccumulator();
674 void reset(InputDevice* device);
676 void process(const RawEvent* rawEvent);
679 inline int32_t getRelativeX() const { return mRelX; }
680 inline int32_t getRelativeY() const { return mRelY; }
686 void clearRelativeAxes();
690 /* Keeps track of cursor scrolling motions. */
692 class CursorScrollAccumulator {
694 CursorScrollAccumulator();
695 void configure(InputDevice* device);
696 void reset(InputDevice* device);
698 void process(const RawEvent* rawEvent);
701 inline bool haveRelativeVWheel() const { return mHaveRelWheel; }
702 inline bool haveRelativeHWheel() const { return mHaveRelHWheel; }
704 inline int32_t getRelativeX() const { return mRelX; }
705 inline int32_t getRelativeY() const { return mRelY; }
706 inline int32_t getRelativeVWheel() const { return mRelWheel; }
707 inline int32_t getRelativeHWheel() const { return mRelHWheel; }
718 void clearRelativeAxes();
722 /* Keeps track of the state of touch, stylus and tool buttons. */
723 class TouchButtonAccumulator {
725 TouchButtonAccumulator();
726 void configure(InputDevice* device);
727 void reset(InputDevice* device);
729 void process(const RawEvent* rawEvent);
731 uint32_t getButtonState() const;
732 int32_t getToolType() const;
733 bool isToolActive() const;
734 bool isHovering() const;
735 bool hasStylus() const;
749 bool mBtnToolAirbrush;
752 bool mBtnToolDoubleTap;
753 bool mBtnToolTripleTap;
754 bool mBtnToolQuadTap;
760 /* Raw axis information from the driver. */
761 struct RawPointerAxes {
762 RawAbsoluteAxisInfo x;
763 RawAbsoluteAxisInfo y;
764 RawAbsoluteAxisInfo pressure;
765 RawAbsoluteAxisInfo touchMajor;
766 RawAbsoluteAxisInfo touchMinor;
767 RawAbsoluteAxisInfo toolMajor;
768 RawAbsoluteAxisInfo toolMinor;
769 RawAbsoluteAxisInfo orientation;
770 RawAbsoluteAxisInfo distance;
771 RawAbsoluteAxisInfo tiltX;
772 RawAbsoluteAxisInfo tiltY;
773 RawAbsoluteAxisInfo trackingId;
774 RawAbsoluteAxisInfo slot;
781 /* Raw data for a collection of pointers including a pointer id mapping table. */
782 struct RawPointerData {
796 int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant
800 uint32_t pointerCount;
801 Pointer pointers[MAX_POINTERS];
802 BitSet32 hoveringIdBits, touchingIdBits;
803 uint32_t idToIndex[MAX_POINTER_ID + 1];
807 void copyFrom(const RawPointerData& other);
808 void getCentroidOfTouchingPointers(float* outX, float* outY) const;
810 inline void markIdBit(uint32_t id, bool isHovering) {
812 hoveringIdBits.markBit(id);
814 touchingIdBits.markBit(id);
818 inline void clearIdBits() {
819 hoveringIdBits.clear();
820 touchingIdBits.clear();
823 inline const Pointer& pointerForId(uint32_t id) const {
824 return pointers[idToIndex[id]];
827 inline bool isHovering(uint32_t pointerIndex) {
828 return pointers[pointerIndex].isHovering;
833 /* Cooked data for a collection of pointers including a pointer id mapping table. */
834 struct CookedPointerData {
835 uint32_t pointerCount;
836 PointerProperties pointerProperties[MAX_POINTERS];
837 PointerCoords pointerCoords[MAX_POINTERS];
838 BitSet32 hoveringIdBits, touchingIdBits;
839 uint32_t idToIndex[MAX_POINTER_ID + 1];
843 void copyFrom(const CookedPointerData& other);
845 inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
846 return pointerCoords[idToIndex[id]];
849 inline PointerCoords& editPointerCoordsWithId(uint32_t id) {
850 return pointerCoords[idToIndex[id]];
853 inline PointerProperties& editPointerPropertiesWithId(uint32_t id) {
854 return pointerProperties[idToIndex[id]];
857 inline bool isHovering(uint32_t pointerIndex) const {
858 return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
861 inline bool isTouching(uint32_t pointerIndex) const {
862 return touchingIdBits.hasBit(pointerProperties[pointerIndex].id);
867 /* Keeps track of the state of single-touch protocol. */
868 class SingleTouchMotionAccumulator {
870 SingleTouchMotionAccumulator();
872 void process(const RawEvent* rawEvent);
873 void reset(InputDevice* device);
875 inline int32_t getAbsoluteX() const { return mAbsX; }
876 inline int32_t getAbsoluteY() const { return mAbsY; }
877 inline int32_t getAbsolutePressure() const { return mAbsPressure; }
878 inline int32_t getAbsoluteToolWidth() const { return mAbsToolWidth; }
879 inline int32_t getAbsoluteDistance() const { return mAbsDistance; }
880 inline int32_t getAbsoluteTiltX() const { return mAbsTiltX; }
881 inline int32_t getAbsoluteTiltY() const { return mAbsTiltY; }
886 int32_t mAbsPressure;
887 int32_t mAbsToolWidth;
888 int32_t mAbsDistance;
892 void clearAbsoluteAxes();
896 /* Keeps track of the state of multi-touch protocol. */
897 class MultiTouchMotionAccumulator {
901 inline bool isInUse() const { return mInUse; }
902 inline int32_t getX() const { return mAbsMTPositionX; }
903 inline int32_t getY() const { return mAbsMTPositionY; }
904 inline int32_t getTouchMajor() const { return mAbsMTTouchMajor; }
905 inline int32_t getTouchMinor() const {
906 return mHaveAbsMTTouchMinor ? mAbsMTTouchMinor : mAbsMTTouchMajor; }
907 inline int32_t getToolMajor() const { return mAbsMTWidthMajor; }
908 inline int32_t getToolMinor() const {
909 return mHaveAbsMTWidthMinor ? mAbsMTWidthMinor : mAbsMTWidthMajor; }
910 inline int32_t getOrientation() const { return mAbsMTOrientation; }
911 inline int32_t getTrackingId() const { return mAbsMTTrackingId; }
912 inline int32_t getPressure() const { return mAbsMTPressure; }
913 inline int32_t getDistance() const { return mAbsMTDistance; }
914 inline int32_t getToolType() const;
917 friend class MultiTouchMotionAccumulator;
920 bool mHaveAbsMTTouchMinor;
921 bool mHaveAbsMTWidthMinor;
922 bool mHaveAbsMTToolType;
924 int32_t mAbsMTPositionX;
925 int32_t mAbsMTPositionY;
926 int32_t mAbsMTTouchMajor;
927 int32_t mAbsMTTouchMinor;
928 int32_t mAbsMTWidthMajor;
929 int32_t mAbsMTWidthMinor;
930 int32_t mAbsMTOrientation;
931 int32_t mAbsMTTrackingId;
932 int32_t mAbsMTPressure;
933 int32_t mAbsMTDistance;
934 int32_t mAbsMTToolType;
940 MultiTouchMotionAccumulator();
941 ~MultiTouchMotionAccumulator();
943 void configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol);
944 void reset(InputDevice* device);
945 void process(const RawEvent* rawEvent);
947 bool hasStylus() const;
949 inline size_t getSlotCount() const { return mSlotCount; }
950 inline const Slot* getSlot(size_t index) const { return &mSlots[index]; }
953 int32_t mCurrentSlot;
956 bool mUsingSlotsProtocol;
959 void clearSlots(int32_t initialSlot);
963 /* An input mapper transforms raw input events into cooked event data.
964 * A single input device can have multiple associated input mappers in order to interpret
965 * different classes of events.
967 * InputMapper lifecycle:
969 * - configure with 0 changes
971 * - process, process, process (may occasionally reconfigure with non-zero changes or reset)
977 explicit InputMapper(InputDevice* device);
978 virtual ~InputMapper();
980 inline InputDevice* getDevice() { return mDevice; }
981 inline int32_t getDeviceId() { return mDevice->getId(); }
982 inline const String8 getDeviceName() { return mDevice->getName(); }
983 inline InputReaderContext* getContext() { return mContext; }
984 inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
985 inline InputListenerInterface* getListener() { return mContext->getListener(); }
986 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
988 virtual uint32_t getSources() = 0;
989 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
990 virtual void dump(String8& dump);
991 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
992 virtual void reset(nsecs_t when);
993 virtual void process(const RawEvent* rawEvent) = 0;
994 virtual void timeoutExpired(nsecs_t when);
996 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
997 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
998 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
999 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1000 const int32_t* keyCodes, uint8_t* outFlags);
1001 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1003 virtual void cancelVibrate(int32_t token);
1004 virtual void cancelTouch(nsecs_t when);
1006 virtual int32_t getMetaState();
1007 virtual void updateMetaState(int32_t keyCode);
1009 virtual void updateExternalStylusState(const StylusState& state);
1011 virtual void fadePointer();
1014 InputDevice* mDevice;
1015 InputReaderContext* mContext;
1017 status_t getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo);
1018 void bumpGeneration();
1020 static void dumpRawAbsoluteAxisInfo(String8& dump,
1021 const RawAbsoluteAxisInfo& axis, const char* name);
1022 static void dumpStylusState(String8& dump, const StylusState& state);
1026 class SwitchInputMapper : public InputMapper {
1028 explicit SwitchInputMapper(InputDevice* device);
1029 virtual ~SwitchInputMapper();
1031 virtual uint32_t getSources();
1032 virtual void process(const RawEvent* rawEvent);
1034 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
1035 virtual void dump(String8& dump);
1038 uint32_t mSwitchValues;
1039 uint32_t mUpdatedSwitchMask;
1041 void processSwitch(int32_t switchCode, int32_t switchValue);
1042 void sync(nsecs_t when);
1046 class VibratorInputMapper : public InputMapper {
1048 explicit VibratorInputMapper(InputDevice* device);
1049 virtual ~VibratorInputMapper();
1051 virtual uint32_t getSources();
1052 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1053 virtual void process(const RawEvent* rawEvent);
1055 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1057 virtual void cancelVibrate(int32_t token);
1058 virtual void timeoutExpired(nsecs_t when);
1059 virtual void dump(String8& dump);
1063 nsecs_t mPattern[MAX_VIBRATE_PATTERN_SIZE];
1064 size_t mPatternSize;
1068 nsecs_t mNextStepTime;
1071 void stopVibrating();
1075 class KeyboardInputMapper : public InputMapper {
1077 KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType);
1078 virtual ~KeyboardInputMapper();
1080 virtual uint32_t getSources();
1081 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1082 virtual void dump(String8& dump);
1083 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1084 virtual void reset(nsecs_t when);
1085 virtual void process(const RawEvent* rawEvent);
1087 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1088 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1089 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1090 const int32_t* keyCodes, uint8_t* outFlags);
1092 virtual int32_t getMetaState();
1093 virtual void updateMetaState(int32_t keyCode);
1102 int32_t mKeyboardType;
1104 int32_t mOrientation; // orientation for dpad keys
1106 Vector<KeyDown> mKeyDowns; // keys that are down
1108 nsecs_t mDownTime; // time of most recent key down
1110 int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none
1113 bool avail; // led is available
1114 bool on; // we think the led is currently on
1116 LedState mCapsLockLedState;
1117 LedState mNumLockLedState;
1118 LedState mScrollLockLedState;
1120 // Immutable configuration parameters.
1122 bool hasAssociatedDisplay;
1123 bool orientationAware;
1124 bool handlesKeyRepeat;
1127 void configureParameters();
1128 void dumpParameters(String8& dump);
1130 bool isKeyboardOrGamepadKey(int32_t scanCode);
1132 void processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode);
1134 bool updateMetaStateIfNeeded(int32_t keyCode, bool down);
1136 ssize_t findKeyDown(int32_t scanCode);
1138 void resetLedState();
1139 void initializeLedState(LedState& ledState, int32_t led);
1140 void updateLedState(bool reset);
1141 void updateLedStateForModifier(LedState& ledState, int32_t led,
1142 int32_t modifier, bool reset);
1146 class CursorInputMapper : public InputMapper {
1148 explicit CursorInputMapper(InputDevice* device);
1149 virtual ~CursorInputMapper();
1151 virtual uint32_t getSources();
1152 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1153 virtual void dump(String8& dump);
1154 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1155 virtual void reset(nsecs_t when);
1156 virtual void process(const RawEvent* rawEvent);
1158 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1160 virtual void fadePointer();
1163 // Amount that trackball needs to move in order to generate a key event.
1164 static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
1166 // Immutable configuration parameters.
1170 MODE_POINTER_RELATIVE,
1175 bool hasAssociatedDisplay;
1176 bool orientationAware;
1179 CursorButtonAccumulator mCursorButtonAccumulator;
1180 CursorMotionAccumulator mCursorMotionAccumulator;
1181 CursorScrollAccumulator mCursorScrollAccumulator;
1192 // Velocity controls for mouse pointer and wheel movements.
1193 // The controls for X and Y wheel movements are separate to keep them decoupled.
1194 VelocityControl mPointerVelocityControl;
1195 VelocityControl mWheelXVelocityControl;
1196 VelocityControl mWheelYVelocityControl;
1198 int32_t mOrientation;
1200 sp<PointerControllerInterface> mPointerController;
1202 int32_t mButtonState;
1205 void configureParameters();
1206 void dumpParameters(String8& dump);
1208 void sync(nsecs_t when);
1212 class RotaryEncoderInputMapper : public InputMapper {
1214 explicit RotaryEncoderInputMapper(InputDevice* device);
1215 virtual ~RotaryEncoderInputMapper();
1217 virtual uint32_t getSources();
1218 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1219 virtual void dump(String8& dump);
1220 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1221 virtual void reset(nsecs_t when);
1222 virtual void process(const RawEvent* rawEvent);
1225 CursorScrollAccumulator mRotaryEncoderScrollAccumulator;
1228 float mScalingFactor;
1229 int32_t mOrientation;
1231 void sync(nsecs_t when);
1234 class TouchInputMapper : public InputMapper {
1236 explicit TouchInputMapper(InputDevice* device);
1237 virtual ~TouchInputMapper();
1239 virtual uint32_t getSources();
1240 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1241 virtual void dump(String8& dump);
1242 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1243 virtual void reset(nsecs_t when);
1244 virtual void process(const RawEvent* rawEvent);
1246 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1247 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1248 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1249 const int32_t* keyCodes, uint8_t* outFlags);
1251 virtual void fadePointer();
1252 virtual void cancelTouch(nsecs_t when);
1253 virtual void timeoutExpired(nsecs_t when);
1254 virtual void updateExternalStylusState(const StylusState& state);
1257 CursorButtonAccumulator mCursorButtonAccumulator;
1258 CursorScrollAccumulator mCursorScrollAccumulator;
1259 TouchButtonAccumulator mTouchButtonAccumulator;
1266 // computed hit box, specified in touch screen coords based on known display size
1272 inline bool isHit(int32_t x, int32_t y) const {
1273 return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
1277 // Input sources and device mode.
1281 DEVICE_MODE_DISABLED, // input is disabled
1282 DEVICE_MODE_DIRECT, // direct mapping (touchscreen)
1283 DEVICE_MODE_UNSCALED, // unscaled mapping (touchpad)
1284 DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
1285 DEVICE_MODE_POINTER, // pointer mapping (pointer)
1287 DeviceMode mDeviceMode;
1289 // The reader's configuration.
1290 InputReaderConfiguration mConfig;
1292 // Immutable configuration parameters.
1295 DEVICE_TYPE_TOUCH_SCREEN,
1296 DEVICE_TYPE_TOUCH_PAD,
1297 DEVICE_TYPE_TOUCH_NAVIGATION,
1298 DEVICE_TYPE_POINTER,
1301 DeviceType deviceType;
1302 bool hasAssociatedDisplay;
1303 bool associatedDisplayIsExternal;
1304 bool orientationAware;
1305 bool hasButtonUnderPad;
1306 String8 uniqueDisplayId;
1309 GESTURE_MODE_SINGLE_TOUCH,
1310 GESTURE_MODE_MULTI_TOUCH,
1312 GestureMode gestureMode;
1317 // Immutable calibration parameters in parsed form.
1318 struct Calibration {
1320 enum SizeCalibration {
1321 SIZE_CALIBRATION_DEFAULT,
1322 SIZE_CALIBRATION_NONE,
1323 SIZE_CALIBRATION_GEOMETRIC,
1324 SIZE_CALIBRATION_DIAMETER,
1325 SIZE_CALIBRATION_BOX,
1326 SIZE_CALIBRATION_AREA,
1329 SizeCalibration sizeCalibration;
1335 bool haveSizeIsSummed;
1339 enum PressureCalibration {
1340 PRESSURE_CALIBRATION_DEFAULT,
1341 PRESSURE_CALIBRATION_NONE,
1342 PRESSURE_CALIBRATION_PHYSICAL,
1343 PRESSURE_CALIBRATION_AMPLITUDE,
1346 PressureCalibration pressureCalibration;
1347 bool havePressureScale;
1348 float pressureScale;
1351 enum OrientationCalibration {
1352 ORIENTATION_CALIBRATION_DEFAULT,
1353 ORIENTATION_CALIBRATION_NONE,
1354 ORIENTATION_CALIBRATION_INTERPOLATED,
1355 ORIENTATION_CALIBRATION_VECTOR,
1358 OrientationCalibration orientationCalibration;
1361 enum DistanceCalibration {
1362 DISTANCE_CALIBRATION_DEFAULT,
1363 DISTANCE_CALIBRATION_NONE,
1364 DISTANCE_CALIBRATION_SCALED,
1367 DistanceCalibration distanceCalibration;
1368 bool haveDistanceScale;
1369 float distanceScale;
1371 enum CoverageCalibration {
1372 COVERAGE_CALIBRATION_DEFAULT,
1373 COVERAGE_CALIBRATION_NONE,
1374 COVERAGE_CALIBRATION_BOX,
1377 CoverageCalibration coverageCalibration;
1379 inline void applySizeScaleAndBias(float* outSize) const {
1380 if (haveSizeScale) {
1381 *outSize *= sizeScale;
1384 *outSize += sizeBias;
1392 // Affine location transformation/calibration
1393 struct TouchAffineTransformation mAffineTransform;
1395 RawPointerAxes mRawPointerAxes;
1400 // Raw pointer sample data.
1401 RawPointerData rawPointerData;
1403 int32_t buttonState;
1409 void copyFrom(const RawState& other) {
1411 rawPointerData.copyFrom(other.rawPointerData);
1412 buttonState = other.buttonState;
1413 rawVScroll = other.rawVScroll;
1414 rawHScroll = other.rawHScroll;
1419 rawPointerData.clear();
1426 struct CookedState {
1427 // Cooked pointer sample data.
1428 CookedPointerData cookedPointerData;
1430 // Id bits used to differentiate fingers, stylus and mouse tools.
1431 BitSet32 fingerIdBits;
1432 BitSet32 stylusIdBits;
1433 BitSet32 mouseIdBits;
1435 int32_t buttonState;
1437 void copyFrom(const CookedState& other) {
1438 cookedPointerData.copyFrom(other.cookedPointerData);
1439 fingerIdBits = other.fingerIdBits;
1440 stylusIdBits = other.stylusIdBits;
1441 mouseIdBits = other.mouseIdBits;
1442 buttonState = other.buttonState;
1446 cookedPointerData.clear();
1447 fingerIdBits.clear();
1448 stylusIdBits.clear();
1449 mouseIdBits.clear();
1454 Vector<RawState> mRawStatesPending;
1455 RawState mCurrentRawState;
1456 CookedState mCurrentCookedState;
1457 RawState mLastRawState;
1458 CookedState mLastCookedState;
1460 // State provided by an external stylus
1461 StylusState mExternalStylusState;
1462 int64_t mExternalStylusId;
1463 nsecs_t mExternalStylusFusionTimeout;
1464 bool mExternalStylusDataPending;
1466 // True if we sent a HOVER_ENTER event.
1467 bool mSentHoverEnter;
1469 // Have we assigned pointer IDs for this stream
1470 bool mHavePointerIds;
1472 // Is the current stream of direct touch events aborted
1473 bool mCurrentMotionAborted;
1475 // The time the primary pointer last went down.
1478 // The pointer controller, or null if the device is not a pointer.
1479 sp<PointerControllerInterface> mPointerController;
1481 Vector<VirtualKey> mVirtualKeys;
1483 virtual void configureParameters();
1484 virtual void dumpParameters(String8& dump);
1485 virtual void configureRawPointerAxes();
1486 virtual void dumpRawPointerAxes(String8& dump);
1487 virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
1488 virtual void dumpSurface(String8& dump);
1489 virtual void configureVirtualKeys();
1490 virtual void dumpVirtualKeys(String8& dump);
1491 virtual void parseCalibration();
1492 virtual void resolveCalibration();
1493 virtual void dumpCalibration(String8& dump);
1494 virtual void updateAffineTransformation();
1495 virtual void dumpAffineTransformation(String8& dump);
1496 virtual void resolveExternalStylusPresence();
1497 virtual bool hasStylus() const = 0;
1498 virtual bool hasExternalStylus() const;
1500 virtual void syncTouch(nsecs_t when, RawState* outState) = 0;
1503 // The current viewport.
1504 // The components of the viewport are specified in the display's rotated orientation.
1505 DisplayViewport mViewport;
1507 // The surface orientation, width and height set by configureSurface().
1508 // The width and height are derived from the viewport but are specified
1509 // in the natural orientation.
1510 // The surface origin specifies how the surface coordinates should be translated
1511 // to align with the logical display coordinate space.
1512 // The orientation may be different from the viewport orientation as it specifies
1513 // the rotation of the surface coordinates required to produce the viewport's
1514 // requested orientation, so it will depend on whether the device is orientation aware.
1515 int32_t mSurfaceWidth;
1516 int32_t mSurfaceHeight;
1517 int32_t mSurfaceLeft;
1518 int32_t mSurfaceTop;
1519 int32_t mSurfaceOrientation;
1521 // Translation and scaling factors, orientation-independent.
1530 float mGeometricScale;
1532 float mPressureScale;
1536 float mOrientationScale;
1538 float mDistanceScale;
1546 bool mExternalStylusConnected;
1548 // Oriented motion ranges for input device info.
1549 struct OrientedRanges {
1550 InputDeviceInfo::MotionRange x;
1551 InputDeviceInfo::MotionRange y;
1552 InputDeviceInfo::MotionRange pressure;
1555 InputDeviceInfo::MotionRange size;
1558 InputDeviceInfo::MotionRange touchMajor;
1559 InputDeviceInfo::MotionRange touchMinor;
1562 InputDeviceInfo::MotionRange toolMajor;
1563 InputDeviceInfo::MotionRange toolMinor;
1565 bool haveOrientation;
1566 InputDeviceInfo::MotionRange orientation;
1569 InputDeviceInfo::MotionRange distance;
1572 InputDeviceInfo::MotionRange tilt;
1580 haveTouchSize = false;
1581 haveToolSize = false;
1582 haveOrientation = false;
1583 haveDistance = false;
1588 // Oriented dimensions and precision.
1589 float mOrientedXPrecision;
1590 float mOrientedYPrecision;
1592 struct CurrentVirtualKeyState {
1598 } mCurrentVirtualKey;
1600 // Scale factor for gesture or mouse based pointer movements.
1601 float mPointerXMovementScale;
1602 float mPointerYMovementScale;
1604 // Scale factor for gesture based zooming and other freeform motions.
1605 float mPointerXZoomScale;
1606 float mPointerYZoomScale;
1608 // The maximum swipe width.
1609 float mPointerGestureMaxSwipeWidth;
1611 struct PointerDistanceHeapElement {
1612 uint32_t currentPointerIndex : 8;
1613 uint32_t lastPointerIndex : 8;
1614 uint64_t distance : 48; // squared distance
1619 POINTER_USAGE_GESTURES,
1620 POINTER_USAGE_STYLUS,
1621 POINTER_USAGE_MOUSE,
1623 PointerUsage mPointerUsage;
1625 struct PointerGesture {
1627 // No fingers, button is not pressed.
1628 // Nothing happening.
1631 // No fingers, button is not pressed.
1633 // Emits DOWN and UP events at the pointer location.
1636 // Exactly one finger dragging following a tap.
1637 // Pointer follows the active finger.
1638 // Emits DOWN, MOVE and UP events at the pointer location.
1640 // Detect double-taps when the finger goes up while in TAP_DRAG mode.
1643 // Button is pressed.
1644 // Pointer follows the active finger if there is one. Other fingers are ignored.
1645 // Emits DOWN, MOVE and UP events at the pointer location.
1646 BUTTON_CLICK_OR_DRAG,
1648 // Exactly one finger, button is not pressed.
1649 // Pointer follows the active finger.
1650 // Emits HOVER_MOVE events at the pointer location.
1652 // Detect taps when the finger goes up while in HOVER mode.
1655 // Exactly two fingers but neither have moved enough to clearly indicate
1656 // whether a swipe or freeform gesture was intended. We consider the
1657 // pointer to be pressed so this enables clicking or long-pressing on buttons.
1658 // Pointer does not move.
1659 // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
1662 // Exactly two fingers moving in the same direction, button is not pressed.
1663 // Pointer does not move.
1664 // Emits DOWN, MOVE and UP events with a single pointer coordinate that
1665 // follows the midpoint between both fingers.
1668 // Two or more fingers moving in arbitrary directions, button is not pressed.
1669 // Pointer does not move.
1670 // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
1671 // each finger individually relative to the initial centroid of the finger.
1674 // Waiting for quiet time to end before starting the next gesture.
1678 // Time the first finger went down.
1679 nsecs_t firstTouchTime;
1681 // The active pointer id from the raw touch data.
1682 int32_t activeTouchId; // -1 if none
1684 // The active pointer id from the gesture last delivered to the application.
1685 int32_t activeGestureId; // -1 if none
1687 // Pointer coords and ids for the current and previous pointer gesture.
1688 Mode currentGestureMode;
1689 BitSet32 currentGestureIdBits;
1690 uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
1691 PointerProperties currentGestureProperties[MAX_POINTERS];
1692 PointerCoords currentGestureCoords[MAX_POINTERS];
1694 Mode lastGestureMode;
1695 BitSet32 lastGestureIdBits;
1696 uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
1697 PointerProperties lastGestureProperties[MAX_POINTERS];
1698 PointerCoords lastGestureCoords[MAX_POINTERS];
1700 // Time the pointer gesture last went down.
1703 // Time when the pointer went down for a TAP.
1704 nsecs_t tapDownTime;
1706 // Time when the pointer went up for a TAP.
1709 // Location of initial tap.
1712 // Time we started waiting for quiescence.
1715 // Reference points for multitouch gestures.
1716 float referenceTouchX; // reference touch X/Y coordinates in surface units
1717 float referenceTouchY;
1718 float referenceGestureX; // reference gesture X/Y coordinates in pixels
1719 float referenceGestureY;
1721 // Distance that each pointer has traveled which has not yet been
1722 // subsumed into the reference gesture position.
1723 BitSet32 referenceIdBits;
1727 Delta referenceDeltas[MAX_POINTER_ID + 1];
1729 // Describes how touch ids are mapped to gesture ids for freeform gestures.
1730 uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
1732 // A velocity tracker for determining whether to switch active pointers during drags.
1733 VelocityTracker velocityTracker;
1736 firstTouchTime = LLONG_MIN;
1738 activeGestureId = -1;
1739 currentGestureMode = NEUTRAL;
1740 currentGestureIdBits.clear();
1741 lastGestureMode = NEUTRAL;
1742 lastGestureIdBits.clear();
1744 velocityTracker.clear();
1750 tapDownTime = LLONG_MIN;
1751 tapUpTime = LLONG_MIN;
1754 void resetQuietTime() {
1755 quietTime = LLONG_MIN;
1759 struct PointerSimple {
1760 PointerCoords currentCoords;
1761 PointerProperties currentProperties;
1762 PointerCoords lastCoords;
1763 PointerProperties lastProperties;
1765 // True if the pointer is down.
1768 // True if the pointer is hovering.
1771 // Time the pointer last went down.
1775 currentCoords.clear();
1776 currentProperties.clear();
1778 lastProperties.clear();
1785 // The pointer and scroll velocity controls.
1786 VelocityControl mPointerVelocityControl;
1787 VelocityControl mWheelXVelocityControl;
1788 VelocityControl mWheelYVelocityControl;
1790 void resetExternalStylus();
1791 void clearStylusDataPendingFlags();
1793 void sync(nsecs_t when);
1795 bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
1796 void processRawTouches(bool timeout);
1797 void cookAndDispatch(nsecs_t when);
1798 void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1799 int32_t keyEventAction, int32_t keyEventFlags);
1801 void dispatchTouches(nsecs_t when, uint32_t policyFlags);
1802 void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
1803 void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
1804 void dispatchButtonRelease(nsecs_t when, uint32_t policyFlags);
1805 void dispatchButtonPress(nsecs_t when, uint32_t policyFlags);
1806 const BitSet32& findActiveIdBits(const CookedPointerData& cookedPointerData);
1807 void cookPointerData();
1808 void abortTouches(nsecs_t when, uint32_t policyFlags);
1810 void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
1811 void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
1813 void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
1814 void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
1815 bool preparePointerGestures(nsecs_t when,
1816 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture,
1819 void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
1820 void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
1822 void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
1823 void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
1825 void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
1826 bool down, bool hovering);
1827 void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
1829 bool assignExternalStylusId(const RawState& state, bool timeout);
1830 void applyExternalStylusButtonState(nsecs_t when);
1831 void applyExternalStylusTouchState(nsecs_t when);
1833 // Dispatches a motion event.
1834 // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
1835 // method will take care of setting the index and transmuting the action to DOWN or UP
1836 // it is the first / last pointer to go down / up.
1837 void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
1838 int32_t action, int32_t actionButton,
1839 int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
1840 const PointerProperties* properties, const PointerCoords* coords,
1841 const uint32_t* idToIndex, BitSet32 idBits,
1842 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
1844 // Updates pointer coords and properties for pointers with specified ids that have moved.
1845 // Returns true if any of them changed.
1846 bool updateMovedPointers(const PointerProperties* inProperties,
1847 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
1848 PointerProperties* outProperties, PointerCoords* outCoords,
1849 const uint32_t* outIdToIndex, BitSet32 idBits) const;
1851 bool isPointInsideSurface(int32_t x, int32_t y);
1852 const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
1854 static void assignPointerIds(const RawState* last, RawState* current);
1856 const char* modeToString(DeviceMode deviceMode);
1860 class SingleTouchInputMapper : public TouchInputMapper {
1862 explicit SingleTouchInputMapper(InputDevice* device);
1863 virtual ~SingleTouchInputMapper();
1865 virtual void reset(nsecs_t when);
1866 virtual void process(const RawEvent* rawEvent);
1869 virtual void syncTouch(nsecs_t when, RawState* outState);
1870 virtual void configureRawPointerAxes();
1871 virtual bool hasStylus() const;
1874 SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
1878 class MultiTouchInputMapper : public TouchInputMapper {
1880 explicit MultiTouchInputMapper(InputDevice* device);
1881 virtual ~MultiTouchInputMapper();
1883 virtual void reset(nsecs_t when);
1884 virtual void process(const RawEvent* rawEvent);
1887 virtual void syncTouch(nsecs_t when, RawState* outState);
1888 virtual void configureRawPointerAxes();
1889 virtual bool hasStylus() const;
1892 MultiTouchMotionAccumulator mMultiTouchMotionAccumulator;
1894 // Specifies the pointer id bits that are in use, and their associated tracking id.
1895 BitSet32 mPointerIdBits;
1896 int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1];
1899 class ExternalStylusInputMapper : public InputMapper {
1901 explicit ExternalStylusInputMapper(InputDevice* device);
1902 virtual ~ExternalStylusInputMapper() = default;
1904 virtual uint32_t getSources();
1905 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1906 virtual void dump(String8& dump);
1907 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1908 virtual void reset(nsecs_t when);
1909 virtual void process(const RawEvent* rawEvent);
1910 virtual void sync(nsecs_t when);
1913 SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
1914 RawAbsoluteAxisInfo mRawPressureAxis;
1915 TouchButtonAccumulator mTouchButtonAccumulator;
1917 StylusState mStylusState;
1921 class JoystickInputMapper : public InputMapper {
1923 explicit JoystickInputMapper(InputDevice* device);
1924 virtual ~JoystickInputMapper();
1926 virtual uint32_t getSources();
1927 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1928 virtual void dump(String8& dump);
1929 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1930 virtual void reset(nsecs_t when);
1931 virtual void process(const RawEvent* rawEvent);
1935 RawAbsoluteAxisInfo rawAxisInfo;
1938 bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1940 float scale; // scale factor from raw to normalized values
1941 float offset; // offset to add after scaling for normalization
1942 float highScale; // scale factor from raw to normalized values of high split
1943 float highOffset; // offset to add after scaling for normalization of high split
1945 float min; // normalized inclusive minimum
1946 float max; // normalized inclusive maximum
1947 float flat; // normalized flat region size
1948 float fuzz; // normalized error tolerance
1949 float resolution; // normalized resolution in units/mm
1951 float filter; // filter out small variations of this size
1952 float currentValue; // current value
1953 float newValue; // most recent value
1954 float highCurrentValue; // current value of high split
1955 float highNewValue; // most recent value of high split
1957 void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
1958 bool explicitlyMapped, float scale, float offset,
1959 float highScale, float highOffset,
1960 float min, float max, float flat, float fuzz, float resolution) {
1961 this->rawAxisInfo = rawAxisInfo;
1962 this->axisInfo = axisInfo;
1963 this->explicitlyMapped = explicitlyMapped;
1964 this->scale = scale;
1965 this->offset = offset;
1966 this->highScale = highScale;
1967 this->highOffset = highOffset;
1972 this->resolution = resolution;
1978 this->currentValue = 0;
1980 this->highCurrentValue = 0;
1981 this->highNewValue = 0;
1985 // Axes indexed by raw ABS_* axis index.
1986 KeyedVector<int32_t, Axis> mAxes;
1988 void sync(nsecs_t when, bool force);
1990 bool haveAxis(int32_t axisId);
1991 void pruneAxes(bool ignoreExplicitlyMappedAxes);
1992 bool filterAxes(bool force);
1994 static bool hasValueChangedSignificantly(float filter,
1995 float newValue, float currentValue, float min, float max);
1996 static bool hasMovedNearerToValueWithinFilteredRange(float filter,
1997 float newValue, float currentValue, float thresholdValue);
1999 static bool isCenteredAxis(int32_t axis);
2000 static int32_t getCompatAxis(int32_t axis);
2002 static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info);
2003 static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
2007 } // namespace android
2009 #endif // _UI_INPUT_READER_H