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