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