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