blob: 7a514e06f36051727fd46b783619be117286e86b [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
Tim Kilbourn063ff532015-04-08 10:26:18 -0700558 inline void setMic(bool hasMic) { mHasMic = hasMic; }
559 inline bool hasMic() const { return mHasMic; }
560
Michael Wrightd02c5b62014-02-10 15:10:22 -0800561 inline bool isIgnored() { return mMappers.isEmpty(); }
562
563 void dump(String8& dump);
564 void addMapper(InputMapper* mapper);
565 void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
566 void reset(nsecs_t when);
567 void process(const RawEvent* rawEvents, size_t count);
568 void timeoutExpired(nsecs_t when);
569
570 void getDeviceInfo(InputDeviceInfo* outDeviceInfo);
571 int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
572 int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
573 int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
574 bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
575 const int32_t* keyCodes, uint8_t* outFlags);
576 void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token);
577 void cancelVibrate(int32_t token);
Jeff Brownc9aa6282015-02-11 19:03:28 -0800578 void cancelTouch(nsecs_t when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579
580 int32_t getMetaState();
581
582 void fadePointer();
583
584 void bumpGeneration();
585
586 void notifyReset(nsecs_t when);
587
588 inline const PropertyMap& getConfiguration() { return mConfiguration; }
589 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
590
591 bool hasKey(int32_t code) {
592 return getEventHub()->hasScanCode(mId, code);
593 }
594
595 bool hasAbsoluteAxis(int32_t code) {
596 RawAbsoluteAxisInfo info;
597 getEventHub()->getAbsoluteAxisInfo(mId, code, &info);
598 return info.valid;
599 }
600
601 bool isKeyPressed(int32_t code) {
602 return getEventHub()->getScanCodeState(mId, code) == AKEY_STATE_DOWN;
603 }
604
605 int32_t getAbsoluteAxisValue(int32_t code) {
606 int32_t value;
607 getEventHub()->getAbsoluteAxisValue(mId, code, &value);
608 return value;
609 }
610
611private:
612 InputReaderContext* mContext;
613 int32_t mId;
614 int32_t mGeneration;
615 int32_t mControllerNumber;
616 InputDeviceIdentifier mIdentifier;
617 String8 mAlias;
618 uint32_t mClasses;
619
620 Vector<InputMapper*> mMappers;
621
622 uint32_t mSources;
623 bool mIsExternal;
Tim Kilbourn063ff532015-04-08 10:26:18 -0700624 bool mHasMic;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 bool mDropUntilNextSync;
626
627 typedef int32_t (InputMapper::*GetStateFunc)(uint32_t sourceMask, int32_t code);
628 int32_t getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc);
629
630 PropertyMap mConfiguration;
631};
632
633
634/* Keeps track of the state of mouse or touch pad buttons. */
635class CursorButtonAccumulator {
636public:
637 CursorButtonAccumulator();
638 void reset(InputDevice* device);
639
640 void process(const RawEvent* rawEvent);
641
642 uint32_t getButtonState() const;
643
644private:
645 bool mBtnLeft;
646 bool mBtnRight;
647 bool mBtnMiddle;
648 bool mBtnBack;
649 bool mBtnSide;
650 bool mBtnForward;
651 bool mBtnExtra;
652 bool mBtnTask;
653
654 void clearButtons();
655};
656
657
658/* Keeps track of cursor movements. */
659
660class CursorMotionAccumulator {
661public:
662 CursorMotionAccumulator();
663 void reset(InputDevice* device);
664
665 void process(const RawEvent* rawEvent);
666 void finishSync();
667
668 inline int32_t getRelativeX() const { return mRelX; }
669 inline int32_t getRelativeY() const { return mRelY; }
670
671private:
672 int32_t mRelX;
673 int32_t mRelY;
674
675 void clearRelativeAxes();
676};
677
678
679/* Keeps track of cursor scrolling motions. */
680
681class CursorScrollAccumulator {
682public:
683 CursorScrollAccumulator();
684 void configure(InputDevice* device);
685 void reset(InputDevice* device);
686
687 void process(const RawEvent* rawEvent);
688 void finishSync();
689
690 inline bool haveRelativeVWheel() const { return mHaveRelWheel; }
691 inline bool haveRelativeHWheel() const { return mHaveRelHWheel; }
692
693 inline int32_t getRelativeX() const { return mRelX; }
694 inline int32_t getRelativeY() const { return mRelY; }
695 inline int32_t getRelativeVWheel() const { return mRelWheel; }
696 inline int32_t getRelativeHWheel() const { return mRelHWheel; }
697
698private:
699 bool mHaveRelWheel;
700 bool mHaveRelHWheel;
701
702 int32_t mRelX;
703 int32_t mRelY;
704 int32_t mRelWheel;
705 int32_t mRelHWheel;
706
707 void clearRelativeAxes();
708};
709
710
711/* Keeps track of the state of touch, stylus and tool buttons. */
712class TouchButtonAccumulator {
713public:
714 TouchButtonAccumulator();
715 void configure(InputDevice* device);
716 void reset(InputDevice* device);
717
718 void process(const RawEvent* rawEvent);
719
720 uint32_t getButtonState() const;
721 int32_t getToolType() const;
722 bool isToolActive() const;
723 bool isHovering() const;
724 bool hasStylus() const;
725
726private:
727 bool mHaveBtnTouch;
728 bool mHaveStylus;
729
730 bool mBtnTouch;
731 bool mBtnStylus;
732 bool mBtnStylus2;
733 bool mBtnToolFinger;
734 bool mBtnToolPen;
735 bool mBtnToolRubber;
736 bool mBtnToolBrush;
737 bool mBtnToolPencil;
738 bool mBtnToolAirbrush;
739 bool mBtnToolMouse;
740 bool mBtnToolLens;
741 bool mBtnToolDoubleTap;
742 bool mBtnToolTripleTap;
743 bool mBtnToolQuadTap;
744
745 void clearButtons();
746};
747
748
749/* Raw axis information from the driver. */
750struct RawPointerAxes {
751 RawAbsoluteAxisInfo x;
752 RawAbsoluteAxisInfo y;
753 RawAbsoluteAxisInfo pressure;
754 RawAbsoluteAxisInfo touchMajor;
755 RawAbsoluteAxisInfo touchMinor;
756 RawAbsoluteAxisInfo toolMajor;
757 RawAbsoluteAxisInfo toolMinor;
758 RawAbsoluteAxisInfo orientation;
759 RawAbsoluteAxisInfo distance;
760 RawAbsoluteAxisInfo tiltX;
761 RawAbsoluteAxisInfo tiltY;
762 RawAbsoluteAxisInfo trackingId;
763 RawAbsoluteAxisInfo slot;
764
765 RawPointerAxes();
766 void clear();
767};
768
769
770/* Raw data for a collection of pointers including a pointer id mapping table. */
771struct RawPointerData {
772 struct Pointer {
773 uint32_t id;
774 int32_t x;
775 int32_t y;
776 int32_t pressure;
777 int32_t touchMajor;
778 int32_t touchMinor;
779 int32_t toolMajor;
780 int32_t toolMinor;
781 int32_t orientation;
782 int32_t distance;
783 int32_t tiltX;
784 int32_t tiltY;
785 int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant
786 bool isHovering;
787 };
788
789 uint32_t pointerCount;
790 Pointer pointers[MAX_POINTERS];
791 BitSet32 hoveringIdBits, touchingIdBits;
792 uint32_t idToIndex[MAX_POINTER_ID + 1];
793
794 RawPointerData();
795 void clear();
796 void copyFrom(const RawPointerData& other);
797 void getCentroidOfTouchingPointers(float* outX, float* outY) const;
798
799 inline void markIdBit(uint32_t id, bool isHovering) {
800 if (isHovering) {
801 hoveringIdBits.markBit(id);
802 } else {
803 touchingIdBits.markBit(id);
804 }
805 }
806
807 inline void clearIdBits() {
808 hoveringIdBits.clear();
809 touchingIdBits.clear();
810 }
811
812 inline const Pointer& pointerForId(uint32_t id) const {
813 return pointers[idToIndex[id]];
814 }
815
816 inline bool isHovering(uint32_t pointerIndex) {
817 return pointers[pointerIndex].isHovering;
818 }
819};
820
821
822/* Cooked data for a collection of pointers including a pointer id mapping table. */
823struct CookedPointerData {
824 uint32_t pointerCount;
825 PointerProperties pointerProperties[MAX_POINTERS];
826 PointerCoords pointerCoords[MAX_POINTERS];
827 BitSet32 hoveringIdBits, touchingIdBits;
828 uint32_t idToIndex[MAX_POINTER_ID + 1];
829
830 CookedPointerData();
831 void clear();
832 void copyFrom(const CookedPointerData& other);
833
834 inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
835 return pointerCoords[idToIndex[id]];
836 }
837
838 inline bool isHovering(uint32_t pointerIndex) {
839 return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
840 }
841};
842
843
844/* Keeps track of the state of single-touch protocol. */
845class SingleTouchMotionAccumulator {
846public:
847 SingleTouchMotionAccumulator();
848
849 void process(const RawEvent* rawEvent);
850 void reset(InputDevice* device);
851
852 inline int32_t getAbsoluteX() const { return mAbsX; }
853 inline int32_t getAbsoluteY() const { return mAbsY; }
854 inline int32_t getAbsolutePressure() const { return mAbsPressure; }
855 inline int32_t getAbsoluteToolWidth() const { return mAbsToolWidth; }
856 inline int32_t getAbsoluteDistance() const { return mAbsDistance; }
857 inline int32_t getAbsoluteTiltX() const { return mAbsTiltX; }
858 inline int32_t getAbsoluteTiltY() const { return mAbsTiltY; }
859
860private:
861 int32_t mAbsX;
862 int32_t mAbsY;
863 int32_t mAbsPressure;
864 int32_t mAbsToolWidth;
865 int32_t mAbsDistance;
866 int32_t mAbsTiltX;
867 int32_t mAbsTiltY;
868
869 void clearAbsoluteAxes();
870};
871
872
873/* Keeps track of the state of multi-touch protocol. */
874class MultiTouchMotionAccumulator {
875public:
876 class Slot {
877 public:
878 inline bool isInUse() const { return mInUse; }
879 inline int32_t getX() const { return mAbsMTPositionX; }
880 inline int32_t getY() const { return mAbsMTPositionY; }
881 inline int32_t getTouchMajor() const { return mAbsMTTouchMajor; }
882 inline int32_t getTouchMinor() const {
883 return mHaveAbsMTTouchMinor ? mAbsMTTouchMinor : mAbsMTTouchMajor; }
884 inline int32_t getToolMajor() const { return mAbsMTWidthMajor; }
885 inline int32_t getToolMinor() const {
886 return mHaveAbsMTWidthMinor ? mAbsMTWidthMinor : mAbsMTWidthMajor; }
887 inline int32_t getOrientation() const { return mAbsMTOrientation; }
888 inline int32_t getTrackingId() const { return mAbsMTTrackingId; }
889 inline int32_t getPressure() const { return mAbsMTPressure; }
890 inline int32_t getDistance() const { return mAbsMTDistance; }
891 inline int32_t getToolType() const;
892
893 private:
894 friend class MultiTouchMotionAccumulator;
895
896 bool mInUse;
897 bool mHaveAbsMTTouchMinor;
898 bool mHaveAbsMTWidthMinor;
899 bool mHaveAbsMTToolType;
900
901 int32_t mAbsMTPositionX;
902 int32_t mAbsMTPositionY;
903 int32_t mAbsMTTouchMajor;
904 int32_t mAbsMTTouchMinor;
905 int32_t mAbsMTWidthMajor;
906 int32_t mAbsMTWidthMinor;
907 int32_t mAbsMTOrientation;
908 int32_t mAbsMTTrackingId;
909 int32_t mAbsMTPressure;
910 int32_t mAbsMTDistance;
911 int32_t mAbsMTToolType;
912
913 Slot();
914 void clear();
915 };
916
917 MultiTouchMotionAccumulator();
918 ~MultiTouchMotionAccumulator();
919
920 void configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol);
921 void reset(InputDevice* device);
922 void process(const RawEvent* rawEvent);
923 void finishSync();
924 bool hasStylus() const;
925
926 inline size_t getSlotCount() const { return mSlotCount; }
927 inline const Slot* getSlot(size_t index) const { return &mSlots[index]; }
928
929private:
930 int32_t mCurrentSlot;
931 Slot* mSlots;
932 size_t mSlotCount;
933 bool mUsingSlotsProtocol;
934 bool mHaveStylus;
935
936 void clearSlots(int32_t initialSlot);
937};
938
939
940/* An input mapper transforms raw input events into cooked event data.
941 * A single input device can have multiple associated input mappers in order to interpret
942 * different classes of events.
943 *
944 * InputMapper lifecycle:
945 * - create
946 * - configure with 0 changes
947 * - reset
948 * - process, process, process (may occasionally reconfigure with non-zero changes or reset)
949 * - reset
950 * - destroy
951 */
952class InputMapper {
953public:
954 InputMapper(InputDevice* device);
955 virtual ~InputMapper();
956
957 inline InputDevice* getDevice() { return mDevice; }
958 inline int32_t getDeviceId() { return mDevice->getId(); }
959 inline const String8 getDeviceName() { return mDevice->getName(); }
960 inline InputReaderContext* getContext() { return mContext; }
961 inline InputReaderPolicyInterface* getPolicy() { return mContext->getPolicy(); }
962 inline InputListenerInterface* getListener() { return mContext->getListener(); }
963 inline EventHubInterface* getEventHub() { return mContext->getEventHub(); }
964
965 virtual uint32_t getSources() = 0;
966 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
967 virtual void dump(String8& dump);
968 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
969 virtual void reset(nsecs_t when);
970 virtual void process(const RawEvent* rawEvent) = 0;
971 virtual void timeoutExpired(nsecs_t when);
972
973 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
974 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
975 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
976 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
977 const int32_t* keyCodes, uint8_t* outFlags);
978 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
979 int32_t token);
980 virtual void cancelVibrate(int32_t token);
Jeff Brownc9aa6282015-02-11 19:03:28 -0800981 virtual void cancelTouch(nsecs_t when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982
983 virtual int32_t getMetaState();
984
985 virtual void fadePointer();
986
987protected:
988 InputDevice* mDevice;
989 InputReaderContext* mContext;
990
991 status_t getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo);
992 void bumpGeneration();
993
994 static void dumpRawAbsoluteAxisInfo(String8& dump,
995 const RawAbsoluteAxisInfo& axis, const char* name);
996};
997
998
999class SwitchInputMapper : public InputMapper {
1000public:
1001 SwitchInputMapper(InputDevice* device);
1002 virtual ~SwitchInputMapper();
1003
1004 virtual uint32_t getSources();
1005 virtual void process(const RawEvent* rawEvent);
1006
1007 virtual int32_t getSwitchState(uint32_t sourceMask, int32_t switchCode);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001008 virtual void dump(String8& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010private:
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001011 uint32_t mSwitchValues;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 uint32_t mUpdatedSwitchMask;
1013
1014 void processSwitch(int32_t switchCode, int32_t switchValue);
1015 void sync(nsecs_t when);
1016};
1017
1018
1019class VibratorInputMapper : public InputMapper {
1020public:
1021 VibratorInputMapper(InputDevice* device);
1022 virtual ~VibratorInputMapper();
1023
1024 virtual uint32_t getSources();
1025 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1026 virtual void process(const RawEvent* rawEvent);
1027
1028 virtual void vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1029 int32_t token);
1030 virtual void cancelVibrate(int32_t token);
1031 virtual void timeoutExpired(nsecs_t when);
1032 virtual void dump(String8& dump);
1033
1034private:
1035 bool mVibrating;
1036 nsecs_t mPattern[MAX_VIBRATE_PATTERN_SIZE];
1037 size_t mPatternSize;
1038 ssize_t mRepeat;
1039 int32_t mToken;
1040 ssize_t mIndex;
1041 nsecs_t mNextStepTime;
1042
1043 void nextStep();
1044 void stopVibrating();
1045};
1046
1047
1048class KeyboardInputMapper : public InputMapper {
1049public:
1050 KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType);
1051 virtual ~KeyboardInputMapper();
1052
1053 virtual uint32_t getSources();
1054 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1055 virtual void dump(String8& dump);
1056 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1057 virtual void reset(nsecs_t when);
1058 virtual void process(const RawEvent* rawEvent);
1059
1060 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1061 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1062 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1063 const int32_t* keyCodes, uint8_t* outFlags);
1064
1065 virtual int32_t getMetaState();
1066
1067private:
1068 struct KeyDown {
1069 int32_t keyCode;
1070 int32_t scanCode;
1071 };
1072
1073 uint32_t mSource;
1074 int32_t mKeyboardType;
1075
1076 int32_t mOrientation; // orientation for dpad keys
1077
1078 Vector<KeyDown> mKeyDowns; // keys that are down
1079 int32_t mMetaState;
1080 nsecs_t mDownTime; // time of most recent key down
1081
1082 int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none
1083
1084 struct LedState {
1085 bool avail; // led is available
1086 bool on; // we think the led is currently on
1087 };
1088 LedState mCapsLockLedState;
1089 LedState mNumLockLedState;
1090 LedState mScrollLockLedState;
1091
1092 // Immutable configuration parameters.
1093 struct Parameters {
1094 bool hasAssociatedDisplay;
1095 bool orientationAware;
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07001096 bool handlesKeyRepeat;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001097 } mParameters;
1098
1099 void configureParameters();
1100 void dumpParameters(String8& dump);
1101
1102 bool isKeyboardOrGamepadKey(int32_t scanCode);
1103
1104 void processKey(nsecs_t when, bool down, int32_t keyCode, int32_t scanCode,
1105 uint32_t policyFlags);
1106
1107 ssize_t findKeyDown(int32_t scanCode);
1108
1109 void resetLedState();
1110 void initializeLedState(LedState& ledState, int32_t led);
1111 void updateLedState(bool reset);
1112 void updateLedStateForModifier(LedState& ledState, int32_t led,
1113 int32_t modifier, bool reset);
1114};
1115
1116
1117class CursorInputMapper : public InputMapper {
1118public:
1119 CursorInputMapper(InputDevice* device);
1120 virtual ~CursorInputMapper();
1121
1122 virtual uint32_t getSources();
1123 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1124 virtual void dump(String8& dump);
1125 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1126 virtual void reset(nsecs_t when);
1127 virtual void process(const RawEvent* rawEvent);
1128
1129 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1130
1131 virtual void fadePointer();
1132
1133private:
1134 // Amount that trackball needs to move in order to generate a key event.
1135 static const int32_t TRACKBALL_MOVEMENT_THRESHOLD = 6;
1136
1137 // Immutable configuration parameters.
1138 struct Parameters {
1139 enum Mode {
1140 MODE_POINTER,
1141 MODE_NAVIGATION,
1142 };
1143
1144 Mode mode;
1145 bool hasAssociatedDisplay;
1146 bool orientationAware;
1147 } mParameters;
1148
1149 CursorButtonAccumulator mCursorButtonAccumulator;
1150 CursorMotionAccumulator mCursorMotionAccumulator;
1151 CursorScrollAccumulator mCursorScrollAccumulator;
1152
1153 int32_t mSource;
1154 float mXScale;
1155 float mYScale;
1156 float mXPrecision;
1157 float mYPrecision;
1158
1159 float mVWheelScale;
1160 float mHWheelScale;
1161
1162 // Velocity controls for mouse pointer and wheel movements.
1163 // The controls for X and Y wheel movements are separate to keep them decoupled.
1164 VelocityControl mPointerVelocityControl;
1165 VelocityControl mWheelXVelocityControl;
1166 VelocityControl mWheelYVelocityControl;
1167
1168 int32_t mOrientation;
1169
1170 sp<PointerControllerInterface> mPointerController;
1171
1172 int32_t mButtonState;
1173 nsecs_t mDownTime;
1174
1175 void configureParameters();
1176 void dumpParameters(String8& dump);
1177
1178 void sync(nsecs_t when);
1179};
1180
1181
1182class TouchInputMapper : public InputMapper {
1183public:
1184 TouchInputMapper(InputDevice* device);
1185 virtual ~TouchInputMapper();
1186
1187 virtual uint32_t getSources();
1188 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1189 virtual void dump(String8& dump);
1190 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1191 virtual void reset(nsecs_t when);
1192 virtual void process(const RawEvent* rawEvent);
1193
1194 virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
1195 virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
1196 virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1197 const int32_t* keyCodes, uint8_t* outFlags);
1198
1199 virtual void fadePointer();
Jeff Brownc9aa6282015-02-11 19:03:28 -08001200 virtual void cancelTouch(nsecs_t when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001201 virtual void timeoutExpired(nsecs_t when);
1202
1203protected:
1204 CursorButtonAccumulator mCursorButtonAccumulator;
1205 CursorScrollAccumulator mCursorScrollAccumulator;
1206 TouchButtonAccumulator mTouchButtonAccumulator;
1207
1208 struct VirtualKey {
1209 int32_t keyCode;
1210 int32_t scanCode;
1211 uint32_t flags;
1212
1213 // computed hit box, specified in touch screen coords based on known display size
1214 int32_t hitLeft;
1215 int32_t hitTop;
1216 int32_t hitRight;
1217 int32_t hitBottom;
1218
1219 inline bool isHit(int32_t x, int32_t y) const {
1220 return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
1221 }
1222 };
1223
1224 // Input sources and device mode.
1225 uint32_t mSource;
1226
1227 enum DeviceMode {
1228 DEVICE_MODE_DISABLED, // input is disabled
1229 DEVICE_MODE_DIRECT, // direct mapping (touchscreen)
1230 DEVICE_MODE_UNSCALED, // unscaled mapping (touchpad)
1231 DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
1232 DEVICE_MODE_POINTER, // pointer mapping (pointer)
1233 };
1234 DeviceMode mDeviceMode;
1235
1236 // The reader's configuration.
1237 InputReaderConfiguration mConfig;
1238
1239 // Immutable configuration parameters.
1240 struct Parameters {
1241 enum DeviceType {
1242 DEVICE_TYPE_TOUCH_SCREEN,
1243 DEVICE_TYPE_TOUCH_PAD,
1244 DEVICE_TYPE_TOUCH_NAVIGATION,
1245 DEVICE_TYPE_POINTER,
1246 };
1247
1248 DeviceType deviceType;
1249 bool hasAssociatedDisplay;
1250 bool associatedDisplayIsExternal;
1251 bool orientationAware;
1252 bool hasButtonUnderPad;
1253
1254 enum GestureMode {
1255 GESTURE_MODE_POINTER,
1256 GESTURE_MODE_SPOTS,
1257 };
1258 GestureMode gestureMode;
Jeff Brownc5e24422014-02-26 18:48:51 -08001259
1260 bool wake;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261 } mParameters;
1262
1263 // Immutable calibration parameters in parsed form.
1264 struct Calibration {
1265 // Size
1266 enum SizeCalibration {
1267 SIZE_CALIBRATION_DEFAULT,
1268 SIZE_CALIBRATION_NONE,
1269 SIZE_CALIBRATION_GEOMETRIC,
1270 SIZE_CALIBRATION_DIAMETER,
1271 SIZE_CALIBRATION_BOX,
1272 SIZE_CALIBRATION_AREA,
1273 };
1274
1275 SizeCalibration sizeCalibration;
1276
1277 bool haveSizeScale;
1278 float sizeScale;
1279 bool haveSizeBias;
1280 float sizeBias;
1281 bool haveSizeIsSummed;
1282 bool sizeIsSummed;
1283
1284 // Pressure
1285 enum PressureCalibration {
1286 PRESSURE_CALIBRATION_DEFAULT,
1287 PRESSURE_CALIBRATION_NONE,
1288 PRESSURE_CALIBRATION_PHYSICAL,
1289 PRESSURE_CALIBRATION_AMPLITUDE,
1290 };
1291
1292 PressureCalibration pressureCalibration;
1293 bool havePressureScale;
1294 float pressureScale;
1295
1296 // Orientation
1297 enum OrientationCalibration {
1298 ORIENTATION_CALIBRATION_DEFAULT,
1299 ORIENTATION_CALIBRATION_NONE,
1300 ORIENTATION_CALIBRATION_INTERPOLATED,
1301 ORIENTATION_CALIBRATION_VECTOR,
1302 };
1303
1304 OrientationCalibration orientationCalibration;
1305
1306 // Distance
1307 enum DistanceCalibration {
1308 DISTANCE_CALIBRATION_DEFAULT,
1309 DISTANCE_CALIBRATION_NONE,
1310 DISTANCE_CALIBRATION_SCALED,
1311 };
1312
1313 DistanceCalibration distanceCalibration;
1314 bool haveDistanceScale;
1315 float distanceScale;
1316
1317 enum CoverageCalibration {
1318 COVERAGE_CALIBRATION_DEFAULT,
1319 COVERAGE_CALIBRATION_NONE,
1320 COVERAGE_CALIBRATION_BOX,
1321 };
1322
1323 CoverageCalibration coverageCalibration;
1324
1325 inline void applySizeScaleAndBias(float* outSize) const {
1326 if (haveSizeScale) {
1327 *outSize *= sizeScale;
1328 }
1329 if (haveSizeBias) {
1330 *outSize += sizeBias;
1331 }
1332 if (*outSize < 0) {
1333 *outSize = 0;
1334 }
1335 }
1336 } mCalibration;
1337
Jason Gereckeaf126fb2012-05-10 14:22:47 -07001338 // Affine location transformation/calibration
1339 struct TouchAffineTransformation mAffineTransform;
1340
Michael Wrightd02c5b62014-02-10 15:10:22 -08001341 // Raw pointer axis information from the driver.
1342 RawPointerAxes mRawPointerAxes;
1343
1344 // Raw pointer sample data.
1345 RawPointerData mCurrentRawPointerData;
1346 RawPointerData mLastRawPointerData;
1347
1348 // Cooked pointer sample data.
1349 CookedPointerData mCurrentCookedPointerData;
1350 CookedPointerData mLastCookedPointerData;
1351
1352 // Button state.
1353 int32_t mCurrentButtonState;
1354 int32_t mLastButtonState;
1355
1356 // Scroll state.
1357 int32_t mCurrentRawVScroll;
1358 int32_t mCurrentRawHScroll;
1359
1360 // Id bits used to differentiate fingers, stylus and mouse tools.
1361 BitSet32 mCurrentFingerIdBits; // finger or unknown
1362 BitSet32 mLastFingerIdBits;
1363 BitSet32 mCurrentStylusIdBits; // stylus or eraser
1364 BitSet32 mLastStylusIdBits;
1365 BitSet32 mCurrentMouseIdBits; // mouse or lens
1366 BitSet32 mLastMouseIdBits;
1367
1368 // True if we sent a HOVER_ENTER event.
1369 bool mSentHoverEnter;
1370
1371 // The time the primary pointer last went down.
1372 nsecs_t mDownTime;
1373
1374 // The pointer controller, or null if the device is not a pointer.
1375 sp<PointerControllerInterface> mPointerController;
1376
1377 Vector<VirtualKey> mVirtualKeys;
1378
1379 virtual void configureParameters();
1380 virtual void dumpParameters(String8& dump);
1381 virtual void configureRawPointerAxes();
1382 virtual void dumpRawPointerAxes(String8& dump);
1383 virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
1384 virtual void dumpSurface(String8& dump);
1385 virtual void configureVirtualKeys();
1386 virtual void dumpVirtualKeys(String8& dump);
1387 virtual void parseCalibration();
1388 virtual void resolveCalibration();
1389 virtual void dumpCalibration(String8& dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07001390 virtual void dumpAffineTransformation(String8& dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001391 virtual bool hasStylus() const = 0;
Jason Gerecke12d6baa2014-01-27 18:34:20 -08001392 virtual void updateAffineTransformation();
Michael Wrightd02c5b62014-02-10 15:10:22 -08001393
1394 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds) = 0;
1395
1396private:
1397 // The current viewport.
1398 // The components of the viewport are specified in the display's rotated orientation.
1399 DisplayViewport mViewport;
1400
1401 // The surface orientation, width and height set by configureSurface().
1402 // The width and height are derived from the viewport but are specified
1403 // in the natural orientation.
1404 // The surface origin specifies how the surface coordinates should be translated
1405 // to align with the logical display coordinate space.
1406 // The orientation may be different from the viewport orientation as it specifies
1407 // the rotation of the surface coordinates required to produce the viewport's
1408 // requested orientation, so it will depend on whether the device is orientation aware.
1409 int32_t mSurfaceWidth;
1410 int32_t mSurfaceHeight;
1411 int32_t mSurfaceLeft;
1412 int32_t mSurfaceTop;
1413 int32_t mSurfaceOrientation;
1414
1415 // Translation and scaling factors, orientation-independent.
1416 float mXTranslate;
1417 float mXScale;
1418 float mXPrecision;
1419
1420 float mYTranslate;
1421 float mYScale;
1422 float mYPrecision;
1423
1424 float mGeometricScale;
1425
1426 float mPressureScale;
1427
1428 float mSizeScale;
1429
1430 float mOrientationScale;
1431
1432 float mDistanceScale;
1433
1434 bool mHaveTilt;
1435 float mTiltXCenter;
1436 float mTiltXScale;
1437 float mTiltYCenter;
1438 float mTiltYScale;
1439
1440 // Oriented motion ranges for input device info.
1441 struct OrientedRanges {
1442 InputDeviceInfo::MotionRange x;
1443 InputDeviceInfo::MotionRange y;
1444 InputDeviceInfo::MotionRange pressure;
1445
1446 bool haveSize;
1447 InputDeviceInfo::MotionRange size;
1448
1449 bool haveTouchSize;
1450 InputDeviceInfo::MotionRange touchMajor;
1451 InputDeviceInfo::MotionRange touchMinor;
1452
1453 bool haveToolSize;
1454 InputDeviceInfo::MotionRange toolMajor;
1455 InputDeviceInfo::MotionRange toolMinor;
1456
1457 bool haveOrientation;
1458 InputDeviceInfo::MotionRange orientation;
1459
1460 bool haveDistance;
1461 InputDeviceInfo::MotionRange distance;
1462
1463 bool haveTilt;
1464 InputDeviceInfo::MotionRange tilt;
1465
1466 OrientedRanges() {
1467 clear();
1468 }
1469
1470 void clear() {
1471 haveSize = false;
1472 haveTouchSize = false;
1473 haveToolSize = false;
1474 haveOrientation = false;
1475 haveDistance = false;
1476 haveTilt = false;
1477 }
1478 } mOrientedRanges;
1479
1480 // Oriented dimensions and precision.
1481 float mOrientedXPrecision;
1482 float mOrientedYPrecision;
1483
1484 struct CurrentVirtualKeyState {
1485 bool down;
1486 bool ignored;
1487 nsecs_t downTime;
1488 int32_t keyCode;
1489 int32_t scanCode;
1490 } mCurrentVirtualKey;
1491
1492 // Scale factor for gesture or mouse based pointer movements.
1493 float mPointerXMovementScale;
1494 float mPointerYMovementScale;
1495
1496 // Scale factor for gesture based zooming and other freeform motions.
1497 float mPointerXZoomScale;
1498 float mPointerYZoomScale;
1499
1500 // The maximum swipe width.
1501 float mPointerGestureMaxSwipeWidth;
1502
1503 struct PointerDistanceHeapElement {
1504 uint32_t currentPointerIndex : 8;
1505 uint32_t lastPointerIndex : 8;
1506 uint64_t distance : 48; // squared distance
1507 };
1508
1509 enum PointerUsage {
1510 POINTER_USAGE_NONE,
1511 POINTER_USAGE_GESTURES,
1512 POINTER_USAGE_STYLUS,
1513 POINTER_USAGE_MOUSE,
1514 };
1515 PointerUsage mPointerUsage;
1516
1517 struct PointerGesture {
1518 enum Mode {
1519 // No fingers, button is not pressed.
1520 // Nothing happening.
1521 NEUTRAL,
1522
1523 // No fingers, button is not pressed.
1524 // Tap detected.
1525 // Emits DOWN and UP events at the pointer location.
1526 TAP,
1527
1528 // Exactly one finger dragging following a tap.
1529 // Pointer follows the active finger.
1530 // Emits DOWN, MOVE and UP events at the pointer location.
1531 //
1532 // Detect double-taps when the finger goes up while in TAP_DRAG mode.
1533 TAP_DRAG,
1534
1535 // Button is pressed.
1536 // Pointer follows the active finger if there is one. Other fingers are ignored.
1537 // Emits DOWN, MOVE and UP events at the pointer location.
1538 BUTTON_CLICK_OR_DRAG,
1539
1540 // Exactly one finger, button is not pressed.
1541 // Pointer follows the active finger.
1542 // Emits HOVER_MOVE events at the pointer location.
1543 //
1544 // Detect taps when the finger goes up while in HOVER mode.
1545 HOVER,
1546
1547 // Exactly two fingers but neither have moved enough to clearly indicate
1548 // whether a swipe or freeform gesture was intended. We consider the
1549 // pointer to be pressed so this enables clicking or long-pressing on buttons.
1550 // Pointer does not move.
1551 // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
1552 PRESS,
1553
1554 // Exactly two fingers moving in the same direction, button is not pressed.
1555 // Pointer does not move.
1556 // Emits DOWN, MOVE and UP events with a single pointer coordinate that
1557 // follows the midpoint between both fingers.
1558 SWIPE,
1559
1560 // Two or more fingers moving in arbitrary directions, button is not pressed.
1561 // Pointer does not move.
1562 // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
1563 // each finger individually relative to the initial centroid of the finger.
1564 FREEFORM,
1565
1566 // Waiting for quiet time to end before starting the next gesture.
1567 QUIET,
1568 };
1569
1570 // Time the first finger went down.
1571 nsecs_t firstTouchTime;
1572
1573 // The active pointer id from the raw touch data.
1574 int32_t activeTouchId; // -1 if none
1575
1576 // The active pointer id from the gesture last delivered to the application.
1577 int32_t activeGestureId; // -1 if none
1578
1579 // Pointer coords and ids for the current and previous pointer gesture.
1580 Mode currentGestureMode;
1581 BitSet32 currentGestureIdBits;
1582 uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
1583 PointerProperties currentGestureProperties[MAX_POINTERS];
1584 PointerCoords currentGestureCoords[MAX_POINTERS];
1585
1586 Mode lastGestureMode;
1587 BitSet32 lastGestureIdBits;
1588 uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
1589 PointerProperties lastGestureProperties[MAX_POINTERS];
1590 PointerCoords lastGestureCoords[MAX_POINTERS];
1591
1592 // Time the pointer gesture last went down.
1593 nsecs_t downTime;
1594
1595 // Time when the pointer went down for a TAP.
1596 nsecs_t tapDownTime;
1597
1598 // Time when the pointer went up for a TAP.
1599 nsecs_t tapUpTime;
1600
1601 // Location of initial tap.
1602 float tapX, tapY;
1603
1604 // Time we started waiting for quiescence.
1605 nsecs_t quietTime;
1606
1607 // Reference points for multitouch gestures.
1608 float referenceTouchX; // reference touch X/Y coordinates in surface units
1609 float referenceTouchY;
1610 float referenceGestureX; // reference gesture X/Y coordinates in pixels
1611 float referenceGestureY;
1612
1613 // Distance that each pointer has traveled which has not yet been
1614 // subsumed into the reference gesture position.
1615 BitSet32 referenceIdBits;
1616 struct Delta {
1617 float dx, dy;
1618 };
1619 Delta referenceDeltas[MAX_POINTER_ID + 1];
1620
1621 // Describes how touch ids are mapped to gesture ids for freeform gestures.
1622 uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
1623
1624 // A velocity tracker for determining whether to switch active pointers during drags.
1625 VelocityTracker velocityTracker;
1626
1627 void reset() {
1628 firstTouchTime = LLONG_MIN;
1629 activeTouchId = -1;
1630 activeGestureId = -1;
1631 currentGestureMode = NEUTRAL;
1632 currentGestureIdBits.clear();
1633 lastGestureMode = NEUTRAL;
1634 lastGestureIdBits.clear();
1635 downTime = 0;
1636 velocityTracker.clear();
1637 resetTap();
1638 resetQuietTime();
1639 }
1640
1641 void resetTap() {
1642 tapDownTime = LLONG_MIN;
1643 tapUpTime = LLONG_MIN;
1644 }
1645
1646 void resetQuietTime() {
1647 quietTime = LLONG_MIN;
1648 }
1649 } mPointerGesture;
1650
1651 struct PointerSimple {
1652 PointerCoords currentCoords;
1653 PointerProperties currentProperties;
1654 PointerCoords lastCoords;
1655 PointerProperties lastProperties;
1656
1657 // True if the pointer is down.
1658 bool down;
1659
1660 // True if the pointer is hovering.
1661 bool hovering;
1662
1663 // Time the pointer last went down.
1664 nsecs_t downTime;
1665
1666 void reset() {
1667 currentCoords.clear();
1668 currentProperties.clear();
1669 lastCoords.clear();
1670 lastProperties.clear();
1671 down = false;
1672 hovering = false;
1673 downTime = 0;
1674 }
1675 } mPointerSimple;
1676
1677 // The pointer and scroll velocity controls.
1678 VelocityControl mPointerVelocityControl;
1679 VelocityControl mWheelXVelocityControl;
1680 VelocityControl mWheelYVelocityControl;
1681
1682 void sync(nsecs_t when);
1683
1684 bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
1685 void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1686 int32_t keyEventAction, int32_t keyEventFlags);
1687
1688 void dispatchTouches(nsecs_t when, uint32_t policyFlags);
1689 void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
1690 void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
1691 void cookPointerData();
1692
1693 void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
1694 void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
1695
1696 void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
1697 void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
1698 bool preparePointerGestures(nsecs_t when,
1699 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture,
1700 bool isTimeout);
1701
1702 void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
1703 void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
1704
1705 void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
1706 void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
1707
1708 void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
1709 bool down, bool hovering);
1710 void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
1711
1712 // Dispatches a motion event.
1713 // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
1714 // method will take care of setting the index and transmuting the action to DOWN or UP
1715 // it is the first / last pointer to go down / up.
1716 void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
1717 int32_t action, int32_t flags, int32_t metaState, int32_t buttonState,
1718 int32_t edgeFlags,
1719 const PointerProperties* properties, const PointerCoords* coords,
1720 const uint32_t* idToIndex, BitSet32 idBits,
1721 int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime);
1722
1723 // Updates pointer coords and properties for pointers with specified ids that have moved.
1724 // Returns true if any of them changed.
1725 bool updateMovedPointers(const PointerProperties* inProperties,
1726 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
1727 PointerProperties* outProperties, PointerCoords* outCoords,
1728 const uint32_t* outIdToIndex, BitSet32 idBits) const;
1729
1730 bool isPointInsideSurface(int32_t x, int32_t y);
1731 const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
1732
1733 void assignPointerIds();
1734};
1735
1736
1737class SingleTouchInputMapper : public TouchInputMapper {
1738public:
1739 SingleTouchInputMapper(InputDevice* device);
1740 virtual ~SingleTouchInputMapper();
1741
1742 virtual void reset(nsecs_t when);
1743 virtual void process(const RawEvent* rawEvent);
1744
1745protected:
1746 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1747 virtual void configureRawPointerAxes();
1748 virtual bool hasStylus() const;
1749
1750private:
1751 SingleTouchMotionAccumulator mSingleTouchMotionAccumulator;
1752};
1753
1754
1755class MultiTouchInputMapper : public TouchInputMapper {
1756public:
1757 MultiTouchInputMapper(InputDevice* device);
1758 virtual ~MultiTouchInputMapper();
1759
1760 virtual void reset(nsecs_t when);
1761 virtual void process(const RawEvent* rawEvent);
1762
1763protected:
1764 virtual void syncTouch(nsecs_t when, bool* outHavePointerIds);
1765 virtual void configureRawPointerAxes();
1766 virtual bool hasStylus() const;
1767
1768private:
1769 MultiTouchMotionAccumulator mMultiTouchMotionAccumulator;
1770
1771 // Specifies the pointer id bits that are in use, and their associated tracking id.
1772 BitSet32 mPointerIdBits;
1773 int32_t mPointerTrackingIdMap[MAX_POINTER_ID + 1];
1774};
1775
1776
1777class JoystickInputMapper : public InputMapper {
1778public:
1779 JoystickInputMapper(InputDevice* device);
1780 virtual ~JoystickInputMapper();
1781
1782 virtual uint32_t getSources();
1783 virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
1784 virtual void dump(String8& dump);
1785 virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
1786 virtual void reset(nsecs_t when);
1787 virtual void process(const RawEvent* rawEvent);
1788
1789private:
1790 struct Axis {
1791 RawAbsoluteAxisInfo rawAxisInfo;
1792 AxisInfo axisInfo;
1793
1794 bool explicitlyMapped; // true if the axis was explicitly assigned an axis id
1795
1796 float scale; // scale factor from raw to normalized values
1797 float offset; // offset to add after scaling for normalization
1798 float highScale; // scale factor from raw to normalized values of high split
1799 float highOffset; // offset to add after scaling for normalization of high split
1800
1801 float min; // normalized inclusive minimum
1802 float max; // normalized inclusive maximum
1803 float flat; // normalized flat region size
1804 float fuzz; // normalized error tolerance
1805 float resolution; // normalized resolution in units/mm
1806
1807 float filter; // filter out small variations of this size
1808 float currentValue; // current value
1809 float newValue; // most recent value
1810 float highCurrentValue; // current value of high split
1811 float highNewValue; // most recent value of high split
1812
1813 void initialize(const RawAbsoluteAxisInfo& rawAxisInfo, const AxisInfo& axisInfo,
1814 bool explicitlyMapped, float scale, float offset,
1815 float highScale, float highOffset,
1816 float min, float max, float flat, float fuzz, float resolution) {
1817 this->rawAxisInfo = rawAxisInfo;
1818 this->axisInfo = axisInfo;
1819 this->explicitlyMapped = explicitlyMapped;
1820 this->scale = scale;
1821 this->offset = offset;
1822 this->highScale = highScale;
1823 this->highOffset = highOffset;
1824 this->min = min;
1825 this->max = max;
1826 this->flat = flat;
1827 this->fuzz = fuzz;
1828 this->resolution = resolution;
1829 this->filter = 0;
1830 resetValue();
1831 }
1832
1833 void resetValue() {
1834 this->currentValue = 0;
1835 this->newValue = 0;
1836 this->highCurrentValue = 0;
1837 this->highNewValue = 0;
1838 }
1839 };
1840
1841 // Axes indexed by raw ABS_* axis index.
1842 KeyedVector<int32_t, Axis> mAxes;
1843
1844 void sync(nsecs_t when, bool force);
1845
1846 bool haveAxis(int32_t axisId);
1847 void pruneAxes(bool ignoreExplicitlyMappedAxes);
1848 bool filterAxes(bool force);
1849
1850 static bool hasValueChangedSignificantly(float filter,
1851 float newValue, float currentValue, float min, float max);
1852 static bool hasMovedNearerToValueWithinFilteredRange(float filter,
1853 float newValue, float currentValue, float thresholdValue);
1854
1855 static bool isCenteredAxis(int32_t axis);
1856 static int32_t getCompatAxis(int32_t axis);
1857
1858 static void addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info);
1859 static void setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
1860 float value);
1861};
1862
1863} // namespace android
1864
1865#endif // _UI_INPUT_READER_H