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