blob: 36b206a2d367f2e30f663a1121a8feb41f541965 [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;
Jeff Brownc5e24422014-02-26 18:48:51 -08001219
1220 bool wake;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221 } mParameters;
1222
1223 // Immutable calibration parameters in parsed form.
1224 struct Calibration {
1225 // Size
1226 enum SizeCalibration {
1227 SIZE_CALIBRATION_DEFAULT,
1228 SIZE_CALIBRATION_NONE,
1229 SIZE_CALIBRATION_GEOMETRIC,
1230 SIZE_CALIBRATION_DIAMETER,
1231 SIZE_CALIBRATION_BOX,
1232 SIZE_CALIBRATION_AREA,
1233 };
1234
1235 SizeCalibration sizeCalibration;
1236
1237 bool haveSizeScale;
1238 float sizeScale;
1239 bool haveSizeBias;
1240 float sizeBias;
1241 bool haveSizeIsSummed;
1242 bool sizeIsSummed;
1243
1244 // Pressure
1245 enum PressureCalibration {
1246 PRESSURE_CALIBRATION_DEFAULT,
1247 PRESSURE_CALIBRATION_NONE,
1248 PRESSURE_CALIBRATION_PHYSICAL,
1249 PRESSURE_CALIBRATION_AMPLITUDE,
1250 };
1251
1252 PressureCalibration pressureCalibration;
1253 bool havePressureScale;
1254 float pressureScale;
1255
1256 // Orientation
1257 enum OrientationCalibration {
1258 ORIENTATION_CALIBRATION_DEFAULT,
1259 ORIENTATION_CALIBRATION_NONE,
1260 ORIENTATION_CALIBRATION_INTERPOLATED,
1261 ORIENTATION_CALIBRATION_VECTOR,
1262 };
1263
1264 OrientationCalibration orientationCalibration;
1265
1266 // Distance
1267 enum DistanceCalibration {
1268 DISTANCE_CALIBRATION_DEFAULT,
1269 DISTANCE_CALIBRATION_NONE,
1270 DISTANCE_CALIBRATION_SCALED,
1271 };
1272
1273 DistanceCalibration distanceCalibration;
1274 bool haveDistanceScale;
1275 float distanceScale;
1276
1277 enum CoverageCalibration {
1278 COVERAGE_CALIBRATION_DEFAULT,
1279 COVERAGE_CALIBRATION_NONE,
1280 COVERAGE_CALIBRATION_BOX,
1281 };
1282
1283 CoverageCalibration coverageCalibration;
1284
1285 inline void applySizeScaleAndBias(float* outSize) const {
1286 if (haveSizeScale) {
1287 *outSize *= sizeScale;
1288 }
1289 if (haveSizeBias) {
1290 *outSize += sizeBias;
1291 }
1292 if (*outSize < 0) {
1293 *outSize = 0;
1294 }
1295 }
1296 } mCalibration;
1297
1298 // Raw pointer axis information from the driver.
1299 RawPointerAxes mRawPointerAxes;
1300
1301 // Raw pointer sample data.
1302 RawPointerData mCurrentRawPointerData;
1303 RawPointerData mLastRawPointerData;
1304
1305 // Cooked pointer sample data.
1306 CookedPointerData mCurrentCookedPointerData;
1307 CookedPointerData mLastCookedPointerData;
1308
1309 // Button state.
1310 int32_t mCurrentButtonState;
1311 int32_t mLastButtonState;
1312
1313 // Scroll state.
1314 int32_t mCurrentRawVScroll;
1315 int32_t mCurrentRawHScroll;
1316
1317 // Id bits used to differentiate fingers, stylus and mouse tools.
1318 BitSet32 mCurrentFingerIdBits; // finger or unknown
1319 BitSet32 mLastFingerIdBits;
1320 BitSet32 mCurrentStylusIdBits; // stylus or eraser
1321 BitSet32 mLastStylusIdBits;
1322 BitSet32 mCurrentMouseIdBits; // mouse or lens
1323 BitSet32 mLastMouseIdBits;
1324
1325 // True if we sent a HOVER_ENTER event.
1326 bool mSentHoverEnter;
1327
1328 // The time the primary pointer last went down.
1329 nsecs_t mDownTime;
1330
1331 // The pointer controller, or null if the device is not a pointer.
1332 sp<PointerControllerInterface> mPointerController;
1333
1334 Vector<VirtualKey> mVirtualKeys;
1335
1336 virtual void configureParameters();
1337 virtual void dumpParameters(String8& dump);
1338 virtual void configureRawPointerAxes();
1339 virtual void dumpRawPointerAxes(String8& dump);
1340 virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
1341 virtual void dumpSurface(String8& dump);
1342 virtual void configureVirtualKeys();
1343 virtual void dumpVirtualKeys(String8& dump);
1344 virtual void parseCalibration();
1345 virtual void resolveCalibration();
1346 virtual void dumpCalibration(String8& dump);
1347 virtual bool hasStylus() const = 0;
1348
1349 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds) = 0;
1350
1351private:
1352 // The current viewport.
1353 // The components of the viewport are specified in the display's rotated orientation.
1354 DisplayViewport mViewport;
1355
1356 // The surface orientation, width and height set by configureSurface().
1357 // The width and height are derived from the viewport but are specified
1358 // in the natural orientation.
1359 // The surface origin specifies how the surface coordinates should be translated
1360 // to align with the logical display coordinate space.
1361 // The orientation may be different from the viewport orientation as it specifies
1362 // the rotation of the surface coordinates required to produce the viewport's
1363 // requested orientation, so it will depend on whether the device is orientation aware.
1364 int32_t mSurfaceWidth;
1365 int32_t mSurfaceHeight;
1366 int32_t mSurfaceLeft;
1367 int32_t mSurfaceTop;
1368 int32_t mSurfaceOrientation;
1369
1370 // Translation and scaling factors, orientation-independent.
1371 float mXTranslate;
1372 float mXScale;
1373 float mXPrecision;
1374
1375 float mYTranslate;
1376 float mYScale;
1377 float mYPrecision;
1378
1379 float mGeometricScale;
1380
1381 float mPressureScale;
1382
1383 float mSizeScale;
1384
1385 float mOrientationScale;
1386
1387 float mDistanceScale;
1388
1389 bool mHaveTilt;
1390 float mTiltXCenter;
1391 float mTiltXScale;
1392 float mTiltYCenter;
1393 float mTiltYScale;
1394
1395 // Oriented motion ranges for input device info.
1396 struct OrientedRanges {
1397 InputDeviceInfo::MotionRange x;
1398 InputDeviceInfo::MotionRange y;
1399 InputDeviceInfo::MotionRange pressure;
1400
1401 bool haveSize;
1402 InputDeviceInfo::MotionRange size;
1403
1404 bool haveTouchSize;
1405 InputDeviceInfo::MotionRange touchMajor;
1406 InputDeviceInfo::MotionRange touchMinor;
1407
1408 bool haveToolSize;
1409 InputDeviceInfo::MotionRange toolMajor;
1410 InputDeviceInfo::MotionRange toolMinor;
1411
1412 bool haveOrientation;
1413 InputDeviceInfo::MotionRange orientation;
1414
1415 bool haveDistance;
1416 InputDeviceInfo::MotionRange distance;
1417
1418 bool haveTilt;
1419 InputDeviceInfo::MotionRange tilt;
1420
1421 OrientedRanges() {
1422 clear();
1423 }
1424
1425 void clear() {
1426 haveSize = false;
1427 haveTouchSize = false;
1428 haveToolSize = false;
1429 haveOrientation = false;
1430 haveDistance = false;
1431 haveTilt = false;
1432 }
1433 } mOrientedRanges;
1434
1435 // Oriented dimensions and precision.
1436 float mOrientedXPrecision;
1437 float mOrientedYPrecision;
1438
1439 struct CurrentVirtualKeyState {
1440 bool down;
1441 bool ignored;
1442 nsecs_t downTime;
1443 int32_t keyCode;
1444 int32_t scanCode;
1445 } mCurrentVirtualKey;
1446
1447 // Scale factor for gesture or mouse based pointer movements.
1448 float mPointerXMovementScale;
1449 float mPointerYMovementScale;
1450
1451 // Scale factor for gesture based zooming and other freeform motions.
1452 float mPointerXZoomScale;
1453 float mPointerYZoomScale;
1454
1455 // The maximum swipe width.
1456 float mPointerGestureMaxSwipeWidth;
1457
1458 struct PointerDistanceHeapElement {
1459 uint32_t currentPointerIndex : 8;
1460 uint32_t lastPointerIndex : 8;
1461 uint64_t distance : 48; // squared distance
1462 };
1463
1464 enum PointerUsage {
1465 POINTER_USAGE_NONE,
1466 POINTER_USAGE_GESTURES,
1467 POINTER_USAGE_STYLUS,
1468 POINTER_USAGE_MOUSE,
1469 };
1470 PointerUsage mPointerUsage;
1471
1472 struct PointerGesture {
1473 enum Mode {
1474 // No fingers, button is not pressed.
1475 // Nothing happening.
1476 NEUTRAL,
1477
1478 // No fingers, button is not pressed.
1479 // Tap detected.
1480 // Emits DOWN and UP events at the pointer location.
1481 TAP,
1482
1483 // Exactly one finger dragging following a tap.
1484 // Pointer follows the active finger.
1485 // Emits DOWN, MOVE and UP events at the pointer location.
1486 //
1487 // Detect double-taps when the finger goes up while in TAP_DRAG mode.
1488 TAP_DRAG,
1489
1490 // Button is pressed.
1491 // Pointer follows the active finger if there is one. Other fingers are ignored.
1492 // Emits DOWN, MOVE and UP events at the pointer location.
1493 BUTTON_CLICK_OR_DRAG,
1494
1495 // Exactly one finger, button is not pressed.
1496 // Pointer follows the active finger.
1497 // Emits HOVER_MOVE events at the pointer location.
1498 //
1499 // Detect taps when the finger goes up while in HOVER mode.
1500 HOVER,
1501
1502 // Exactly two fingers but neither have moved enough to clearly indicate
1503 // whether a swipe or freeform gesture was intended. We consider the
1504 // pointer to be pressed so this enables clicking or long-pressing on buttons.
1505 // Pointer does not move.
1506 // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
1507 PRESS,
1508
1509 // Exactly two fingers moving in the same direction, button is not pressed.
1510 // Pointer does not move.
1511 // Emits DOWN, MOVE and UP events with a single pointer coordinate that
1512 // follows the midpoint between both fingers.
1513 SWIPE,
1514
1515 // Two or more fingers moving in arbitrary directions, button is not pressed.
1516 // Pointer does not move.
1517 // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
1518 // each finger individually relative to the initial centroid of the finger.
1519 FREEFORM,
1520
1521 // Waiting for quiet time to end before starting the next gesture.
1522 QUIET,
1523 };
1524
1525 // Time the first finger went down.
1526 nsecs_t firstTouchTime;
1527
1528 // The active pointer id from the raw touch data.
1529 int32_t activeTouchId; // -1 if none
1530
1531 // The active pointer id from the gesture last delivered to the application.
1532 int32_t activeGestureId; // -1 if none
1533
1534 // Pointer coords and ids for the current and previous pointer gesture.
1535 Mode currentGestureMode;
1536 BitSet32 currentGestureIdBits;
1537 uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
1538 PointerProperties currentGestureProperties[MAX_POINTERS];
1539 PointerCoords currentGestureCoords[MAX_POINTERS];
1540
1541 Mode lastGestureMode;
1542 BitSet32 lastGestureIdBits;
1543 uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
1544 PointerProperties lastGestureProperties[MAX_POINTERS];
1545 PointerCoords lastGestureCoords[MAX_POINTERS];
1546
1547 // Time the pointer gesture last went down.
1548 nsecs_t downTime;
1549
1550 // Time when the pointer went down for a TAP.
1551 nsecs_t tapDownTime;
1552
1553 // Time when the pointer went up for a TAP.
1554 nsecs_t tapUpTime;
1555
1556 // Location of initial tap.
1557 float tapX, tapY;
1558
1559 // Time we started waiting for quiescence.
1560 nsecs_t quietTime;
1561
1562 // Reference points for multitouch gestures.
1563 float referenceTouchX; // reference touch X/Y coordinates in surface units
1564 float referenceTouchY;
1565 float referenceGestureX; // reference gesture X/Y coordinates in pixels
1566 float referenceGestureY;
1567
1568 // Distance that each pointer has traveled which has not yet been
1569 // subsumed into the reference gesture position.
1570 BitSet32 referenceIdBits;
1571 struct Delta {
1572 float dx, dy;
1573 };
1574 Delta referenceDeltas[MAX_POINTER_ID + 1];
1575
1576 // Describes how touch ids are mapped to gesture ids for freeform gestures.
1577 uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
1578
1579 // A velocity tracker for determining whether to switch active pointers during drags.
1580 VelocityTracker velocityTracker;
1581
1582 void reset() {
1583 firstTouchTime = LLONG_MIN;
1584 activeTouchId = -1;
1585 activeGestureId = -1;
1586 currentGestureMode = NEUTRAL;
1587 currentGestureIdBits.clear();
1588 lastGestureMode = NEUTRAL;
1589 lastGestureIdBits.clear();
1590 downTime = 0;
1591 velocityTracker.clear();
1592 resetTap();
1593 resetQuietTime();
1594 }
1595
1596 void resetTap() {
1597 tapDownTime = LLONG_MIN;
1598 tapUpTime = LLONG_MIN;
1599 }
1600
1601 void resetQuietTime() {
1602 quietTime = LLONG_MIN;
1603 }
1604 } mPointerGesture;
1605
1606 struct PointerSimple {
1607 PointerCoords currentCoords;
1608 PointerProperties currentProperties;
1609 PointerCoords lastCoords;
1610 PointerProperties lastProperties;
1611
1612 // True if the pointer is down.
1613 bool down;
1614
1615 // True if the pointer is hovering.
1616 bool hovering;
1617
1618 // Time the pointer last went down.
1619 nsecs_t downTime;
1620
1621 void reset() {
1622 currentCoords.clear();
1623 currentProperties.clear();
1624 lastCoords.clear();
1625 lastProperties.clear();
1626 down = false;
1627 hovering = false;
1628 downTime = 0;
1629 }
1630 } mPointerSimple;
1631
1632 // The pointer and scroll velocity controls.
1633 VelocityControl mPointerVelocityControl;
1634 VelocityControl mWheelXVelocityControl;
1635 VelocityControl mWheelYVelocityControl;
1636
1637 void sync(nsecs_t when);
1638
1639 bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
1640 void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1641 int32_t keyEventAction, int32_t keyEventFlags);
1642
1643 void dispatchTouches(nsecs_t when, uint32_t policyFlags);
1644 void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
1645 void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
1646 void cookPointerData();
1647
1648 void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
1649 void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
1650
1651 void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
1652 void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
1653 bool preparePointerGestures(nsecs_t when,
1654 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture,
1655 bool isTimeout);
1656
1657 void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
1658 void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
1659
1660 void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
1661 void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
1662
1663 void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
1664 bool down, bool hovering);
1665 void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
1666
1667 // Dispatches a motion event.
1668 // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
1669 // method will take care of setting the index and transmuting the action to DOWN or UP
1670 // it is the first / last pointer to go down / up.
1671 void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
1672 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
1673 int32_t edgeFlags,
1674 const PointerProperties* properties, const PointerCoords* coords,
1675 const uint32_t* idToIndex, BitSet32 idBits,
1676 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
1677
1678 // Updates pointer coords and properties for pointers with specified ids that have moved.
1679 // Returns true if any of them changed.
1680 bool updateMovedPointers(const PointerProperties* inProperties,
1681 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
1682 PointerProperties* outProperties, PointerCoords* outCoords,
1683 const uint32_t* outIdToIndex, BitSet32 idBits) const;
1684
1685 bool isPointInsideSurface(int32_t x, int32_t y);
1686 const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
1687
1688 void assignPointerIds();
1689};
1690
1691
1692class SingleTouchInputMapper : public TouchInputMapper {
1693public:
1694 SingleTouchInputMapper(InputDevice* device);
1695 virtual ~SingleTouchInputMapper();
1696
1697 virtual void reset(nsecs_t when);
1698 virtual void process(const RawEvent* rawEvent);
1699
1700protected:
1701 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1702 virtual void configureRawPointerAxes();
1703 virtual bool hasStylus() const;
1704
1705private:
1706 SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
1707};
1708
1709
1710class MultiTouchInputMapper : public TouchInputMapper {
1711public:
1712 MultiTouchInputMapper(InputDevice* device);
1713 virtual ~MultiTouchInputMapper();
1714
1715 virtual void reset(nsecs_t when);
1716 virtual void process(const RawEvent* rawEvent);
1717
1718protected:
1719 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1720 virtual void configureRawPointerAxes();
1721 virtual bool hasStylus() const;
1722
1723private:
1724 MultiTouchMotionAccumulator mMultiTouchMotionAccumulator;
1725
1726 // Specifies the pointer id bits that are in use, and their associated tracking id.
1727 BitSet32 mPointerIdBits;
1728 int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1];
1729};
1730
1731
1732class JoystickInputMapper : public InputMapper {
1733public:
1734 JoystickInputMapper(InputDevice* device);
1735 virtual ~JoystickInputMapper();
1736
1737 virtual uint32_t getSources();
1738 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1739 virtual void dump(String8& dump);
1740 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1741 virtual void reset(nsecs_t when);
1742 virtual void process(const RawEvent* rawEvent);
1743
1744private:
1745 struct Axis {
1746 RawAbsoluteAxisInfo rawAxisInfo;
1747 AxisInfo axisInfo;
1748
1749 bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1750
1751 float scale; // scale factor from raw to normalized values
1752 float offset; // offset to add after scaling for normalization
1753 float highScale; // scale factor from raw to normalized values of high split
1754 float highOffset; // offset to add after scaling for normalization of high split
1755
1756 float min; // normalized inclusive minimum
1757 float max; // normalized inclusive maximum
1758 float flat; // normalized flat region size
1759 float fuzz; // normalized error tolerance
1760 float resolution; // normalized resolution in units/mm
1761
1762 float filter; // filter out small variations of this size
1763 float currentValue; // current value
1764 float newValue; // most recent value
1765 float highCurrentValue; // current value of high split
1766 float highNewValue; // most recent value of high split
1767
1768 void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
1769 bool explicitlyMapped, float scale, float offset,
1770 float highScale, float highOffset,
1771 float min, float max, float flat, float fuzz, float resolution) {
1772 this->rawAxisInfo = rawAxisInfo;
1773 this->axisInfo = axisInfo;
1774 this->explicitlyMapped = explicitlyMapped;
1775 this->scale = scale;
1776 this->offset = offset;
1777 this->highScale = highScale;
1778 this->highOffset = highOffset;
1779 this->min = min;
1780 this->max = max;
1781 this->flat = flat;
1782 this->fuzz = fuzz;
1783 this->resolution = resolution;
1784 this->filter = 0;
1785 resetValue();
1786 }
1787
1788 void resetValue() {
1789 this->currentValue = 0;
1790 this->newValue = 0;
1791 this->highCurrentValue = 0;
1792 this->highNewValue = 0;
1793 }
1794 };
1795
1796 // Axes indexed by raw ABS_* axis index.
1797 KeyedVector<int32_t, Axis> mAxes;
1798
1799 void sync(nsecs_t when, bool force);
1800
1801 bool haveAxis(int32_t axisId);
1802 void pruneAxes(bool ignoreExplicitlyMappedAxes);
1803 bool filterAxes(bool force);
1804
1805 static bool hasValueChangedSignificantly(float filter,
1806 float newValue, float currentValue, float min, float max);
1807 static bool hasMovedNearerToValueWithinFilteredRange(float filter,
1808 float newValue, float currentValue, float thresholdValue);
1809
1810 static bool isCenteredAxis(int32_t axis);
1811 static int32_t getCompatAxis(int32_t axis);
1812
1813 static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info);
1814 static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
1815 float value);
1816};
1817
1818} // namespace android
1819
1820#endif // _UI_INPUT_READER_H