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