1 /*
2  * Copyright (C) 2019 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_INPUTREADER_TOUCH_INPUT_MAPPER_H
18 #define _UI_INPUTREADER_TOUCH_INPUT_MAPPER_H
19 
20 #include "CursorButtonAccumulator.h"
21 #include "CursorScrollAccumulator.h"
22 #include "EventHub.h"
23 #include "InputMapper.h"
24 #include "InputReaderBase.h"
25 #include "TouchButtonAccumulator.h"
26 
27 #include <stdint.h>
28 
29 namespace android {
30 
31 /**
32  * Basic statistics information.
33  * Keep track of min, max, average, and standard deviation of the received samples.
34  * Used to report latency information about input events.
35  */
36 struct LatencyStatistics {
37     float min;
38     float max;
39     // Sum of all samples
40     float sum;
41     // Sum of squares of all samples
42     float sum2;
43     // The number of samples
44     size_t count;
45     // The last time statistics were reported.
46     nsecs_t lastReportTime;
47 
LatencyStatisticsLatencyStatistics48     LatencyStatistics() { reset(systemTime(SYSTEM_TIME_MONOTONIC)); }
49 
addValueLatencyStatistics50     inline void addValue(float x) {
51         if (x < min) {
52             min = x;
53         }
54         if (x > max) {
55             max = x;
56         }
57         sum += x;
58         sum2 += x * x;
59         count++;
60     }
61 
62     // Get the average value. Should not be called if no samples have been added.
meanLatencyStatistics63     inline float mean() {
64         if (count == 0) {
65             return 0;
66         }
67         return sum / count;
68     }
69 
70     // Get the standard deviation. Should not be called if no samples have been added.
stdevLatencyStatistics71     inline float stdev() {
72         if (count == 0) {
73             return 0;
74         }
75         float average = mean();
76         return sqrt(sum2 / count - average * average);
77     }
78 
79     /**
80      * Reset internal state. The variable 'when' is the time when the data collection started.
81      * Call this to start a new data collection window.
82      */
resetLatencyStatistics83     inline void reset(nsecs_t when) {
84         max = 0;
85         min = std::numeric_limits<float>::max();
86         sum = 0;
87         sum2 = 0;
88         count = 0;
89         lastReportTime = when;
90     }
91 };
92 
93 /* Raw axis information from the driver. */
94 struct RawPointerAxes {
95     RawAbsoluteAxisInfo x;
96     RawAbsoluteAxisInfo y;
97     RawAbsoluteAxisInfo pressure;
98     RawAbsoluteAxisInfo touchMajor;
99     RawAbsoluteAxisInfo touchMinor;
100     RawAbsoluteAxisInfo toolMajor;
101     RawAbsoluteAxisInfo toolMinor;
102     RawAbsoluteAxisInfo orientation;
103     RawAbsoluteAxisInfo distance;
104     RawAbsoluteAxisInfo tiltX;
105     RawAbsoluteAxisInfo tiltY;
106     RawAbsoluteAxisInfo trackingId;
107     RawAbsoluteAxisInfo slot;
108 
109     RawPointerAxes();
getRawWidthRawPointerAxes110     inline int32_t getRawWidth() const { return x.maxValue - x.minValue + 1; }
getRawHeightRawPointerAxes111     inline int32_t getRawHeight() const { return y.maxValue - y.minValue + 1; }
112     void clear();
113 };
114 
115 /* Raw data for a collection of pointers including a pointer id mapping table. */
116 struct RawPointerData {
117     struct Pointer {
118         uint32_t id;
119         int32_t x;
120         int32_t y;
121         int32_t pressure;
122         int32_t touchMajor;
123         int32_t touchMinor;
124         int32_t toolMajor;
125         int32_t toolMinor;
126         int32_t orientation;
127         int32_t distance;
128         int32_t tiltX;
129         int32_t tiltY;
130         int32_t toolType; // a fully decoded AMOTION_EVENT_TOOL_TYPE constant
131         bool isHovering;
132     };
133 
134     uint32_t pointerCount;
135     Pointer pointers[MAX_POINTERS];
136     BitSet32 hoveringIdBits, touchingIdBits;
137     uint32_t idToIndex[MAX_POINTER_ID + 1];
138 
139     RawPointerData();
140     void clear();
141     void copyFrom(const RawPointerData& other);
142     void getCentroidOfTouchingPointers(float* outX, float* outY) const;
143 
markIdBitRawPointerData144     inline void markIdBit(uint32_t id, bool isHovering) {
145         if (isHovering) {
146             hoveringIdBits.markBit(id);
147         } else {
148             touchingIdBits.markBit(id);
149         }
150     }
151 
clearIdBitsRawPointerData152     inline void clearIdBits() {
153         hoveringIdBits.clear();
154         touchingIdBits.clear();
155     }
156 
pointerForIdRawPointerData157     inline const Pointer& pointerForId(uint32_t id) const { return pointers[idToIndex[id]]; }
158 
isHoveringRawPointerData159     inline bool isHovering(uint32_t pointerIndex) { return pointers[pointerIndex].isHovering; }
160 };
161 
162 /* Cooked data for a collection of pointers including a pointer id mapping table. */
163 struct CookedPointerData {
164     uint32_t pointerCount;
165     PointerProperties pointerProperties[MAX_POINTERS];
166     PointerCoords pointerCoords[MAX_POINTERS];
167     BitSet32 hoveringIdBits, touchingIdBits;
168     uint32_t idToIndex[MAX_POINTER_ID + 1];
169 
170     CookedPointerData();
171     void clear();
172     void copyFrom(const CookedPointerData& other);
173 
pointerCoordsForIdCookedPointerData174     inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
175         return pointerCoords[idToIndex[id]];
176     }
177 
editPointerCoordsWithIdCookedPointerData178     inline PointerCoords& editPointerCoordsWithId(uint32_t id) {
179         return pointerCoords[idToIndex[id]];
180     }
181 
editPointerPropertiesWithIdCookedPointerData182     inline PointerProperties& editPointerPropertiesWithId(uint32_t id) {
183         return pointerProperties[idToIndex[id]];
184     }
185 
isHoveringCookedPointerData186     inline bool isHovering(uint32_t pointerIndex) const {
187         return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
188     }
189 
isTouchingCookedPointerData190     inline bool isTouching(uint32_t pointerIndex) const {
191         return touchingIdBits.hasBit(pointerProperties[pointerIndex].id);
192     }
193 };
194 
195 class TouchInputMapper : public InputMapper {
196 public:
197     explicit TouchInputMapper(InputDevice* device);
198     virtual ~TouchInputMapper();
199 
200     virtual uint32_t getSources();
201     virtual void populateDeviceInfo(InputDeviceInfo* deviceInfo);
202     virtual void dump(std::string& dump);
203     virtual void configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes);
204     virtual void reset(nsecs_t when);
205     virtual void process(const RawEvent* rawEvent);
206 
207     virtual int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode);
208     virtual int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode);
209     virtual bool markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
210                                        const int32_t* keyCodes, uint8_t* outFlags);
211 
212     virtual void fadePointer();
213     virtual void cancelTouch(nsecs_t when);
214     virtual void timeoutExpired(nsecs_t when);
215     virtual void updateExternalStylusState(const StylusState& state);
216     virtual std::optional<int32_t> getAssociatedDisplay();
217 
218 protected:
219     CursorButtonAccumulator mCursorButtonAccumulator;
220     CursorScrollAccumulator mCursorScrollAccumulator;
221     TouchButtonAccumulator mTouchButtonAccumulator;
222 
223     struct VirtualKey {
224         int32_t keyCode;
225         int32_t scanCode;
226         uint32_t flags;
227 
228         // computed hit box, specified in touch screen coords based on known display size
229         int32_t hitLeft;
230         int32_t hitTop;
231         int32_t hitRight;
232         int32_t hitBottom;
233 
isHitVirtualKey234         inline bool isHit(int32_t x, int32_t y) const {
235             return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
236         }
237     };
238 
239     // Input sources and device mode.
240     uint32_t mSource;
241 
242     enum DeviceMode {
243         DEVICE_MODE_DISABLED,   // input is disabled
244         DEVICE_MODE_DIRECT,     // direct mapping (touchscreen)
245         DEVICE_MODE_UNSCALED,   // unscaled mapping (touchpad)
246         DEVICE_MODE_NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
247         DEVICE_MODE_POINTER,    // pointer mapping (pointer)
248     };
249     DeviceMode mDeviceMode;
250 
251     // The reader's configuration.
252     InputReaderConfiguration mConfig;
253 
254     // Immutable configuration parameters.
255     struct Parameters {
256         enum DeviceType {
257             DEVICE_TYPE_TOUCH_SCREEN,
258             DEVICE_TYPE_TOUCH_PAD,
259             DEVICE_TYPE_TOUCH_NAVIGATION,
260             DEVICE_TYPE_POINTER,
261         };
262 
263         DeviceType deviceType;
264         bool hasAssociatedDisplay;
265         bool associatedDisplayIsExternal;
266         bool orientationAware;
267         bool hasButtonUnderPad;
268         std::string uniqueDisplayId;
269 
270         enum GestureMode {
271             GESTURE_MODE_SINGLE_TOUCH,
272             GESTURE_MODE_MULTI_TOUCH,
273         };
274         GestureMode gestureMode;
275 
276         bool wake;
277     } mParameters;
278 
279     // Immutable calibration parameters in parsed form.
280     struct Calibration {
281         // Size
282         enum SizeCalibration {
283             SIZE_CALIBRATION_DEFAULT,
284             SIZE_CALIBRATION_NONE,
285             SIZE_CALIBRATION_GEOMETRIC,
286             SIZE_CALIBRATION_DIAMETER,
287             SIZE_CALIBRATION_BOX,
288             SIZE_CALIBRATION_AREA,
289         };
290 
291         SizeCalibration sizeCalibration;
292 
293         bool haveSizeScale;
294         float sizeScale;
295         bool haveSizeBias;
296         float sizeBias;
297         bool haveSizeIsSummed;
298         bool sizeIsSummed;
299 
300         // Pressure
301         enum PressureCalibration {
302             PRESSURE_CALIBRATION_DEFAULT,
303             PRESSURE_CALIBRATION_NONE,
304             PRESSURE_CALIBRATION_PHYSICAL,
305             PRESSURE_CALIBRATION_AMPLITUDE,
306         };
307 
308         PressureCalibration pressureCalibration;
309         bool havePressureScale;
310         float pressureScale;
311 
312         // Orientation
313         enum OrientationCalibration {
314             ORIENTATION_CALIBRATION_DEFAULT,
315             ORIENTATION_CALIBRATION_NONE,
316             ORIENTATION_CALIBRATION_INTERPOLATED,
317             ORIENTATION_CALIBRATION_VECTOR,
318         };
319 
320         OrientationCalibration orientationCalibration;
321 
322         // Distance
323         enum DistanceCalibration {
324             DISTANCE_CALIBRATION_DEFAULT,
325             DISTANCE_CALIBRATION_NONE,
326             DISTANCE_CALIBRATION_SCALED,
327         };
328 
329         DistanceCalibration distanceCalibration;
330         bool haveDistanceScale;
331         float distanceScale;
332 
333         enum CoverageCalibration {
334             COVERAGE_CALIBRATION_DEFAULT,
335             COVERAGE_CALIBRATION_NONE,
336             COVERAGE_CALIBRATION_BOX,
337         };
338 
339         CoverageCalibration coverageCalibration;
340 
applySizeScaleAndBiasCalibration341         inline void applySizeScaleAndBias(float* outSize) const {
342             if (haveSizeScale) {
343                 *outSize *= sizeScale;
344             }
345             if (haveSizeBias) {
346                 *outSize += sizeBias;
347             }
348             if (*outSize < 0) {
349                 *outSize = 0;
350             }
351         }
352     } mCalibration;
353 
354     // Affine location transformation/calibration
355     struct TouchAffineTransformation mAffineTransform;
356 
357     RawPointerAxes mRawPointerAxes;
358 
359     struct RawState {
360         nsecs_t when;
361         uint32_t deviceTimestamp;
362 
363         // Raw pointer sample data.
364         RawPointerData rawPointerData;
365 
366         int32_t buttonState;
367 
368         // Scroll state.
369         int32_t rawVScroll;
370         int32_t rawHScroll;
371 
copyFromRawState372         void copyFrom(const RawState& other) {
373             when = other.when;
374             deviceTimestamp = other.deviceTimestamp;
375             rawPointerData.copyFrom(other.rawPointerData);
376             buttonState = other.buttonState;
377             rawVScroll = other.rawVScroll;
378             rawHScroll = other.rawHScroll;
379         }
380 
clearRawState381         void clear() {
382             when = 0;
383             deviceTimestamp = 0;
384             rawPointerData.clear();
385             buttonState = 0;
386             rawVScroll = 0;
387             rawHScroll = 0;
388         }
389     };
390 
391     struct CookedState {
392         uint32_t deviceTimestamp;
393         // Cooked pointer sample data.
394         CookedPointerData cookedPointerData;
395 
396         // Id bits used to differentiate fingers, stylus and mouse tools.
397         BitSet32 fingerIdBits;
398         BitSet32 stylusIdBits;
399         BitSet32 mouseIdBits;
400 
401         int32_t buttonState;
402 
copyFromCookedState403         void copyFrom(const CookedState& other) {
404             deviceTimestamp = other.deviceTimestamp;
405             cookedPointerData.copyFrom(other.cookedPointerData);
406             fingerIdBits = other.fingerIdBits;
407             stylusIdBits = other.stylusIdBits;
408             mouseIdBits = other.mouseIdBits;
409             buttonState = other.buttonState;
410         }
411 
clearCookedState412         void clear() {
413             deviceTimestamp = 0;
414             cookedPointerData.clear();
415             fingerIdBits.clear();
416             stylusIdBits.clear();
417             mouseIdBits.clear();
418             buttonState = 0;
419         }
420     };
421 
422     std::vector<RawState> mRawStatesPending;
423     RawState mCurrentRawState;
424     CookedState mCurrentCookedState;
425     RawState mLastRawState;
426     CookedState mLastCookedState;
427 
428     // State provided by an external stylus
429     StylusState mExternalStylusState;
430     int64_t mExternalStylusId;
431     nsecs_t mExternalStylusFusionTimeout;
432     bool mExternalStylusDataPending;
433 
434     // True if we sent a HOVER_ENTER event.
435     bool mSentHoverEnter;
436 
437     // Have we assigned pointer IDs for this stream
438     bool mHavePointerIds;
439 
440     // Is the current stream of direct touch events aborted
441     bool mCurrentMotionAborted;
442 
443     // The time the primary pointer last went down.
444     nsecs_t mDownTime;
445 
446     // The pointer controller, or null if the device is not a pointer.
447     std::shared_ptr<PointerControllerInterface> mPointerController;
448 
449     std::vector<VirtualKey> mVirtualKeys;
450 
451     virtual void configureParameters();
452     virtual void dumpParameters(std::string& dump);
453     virtual void configureRawPointerAxes();
454     virtual void dumpRawPointerAxes(std::string& dump);
455     virtual void configureSurface(nsecs_t when, bool* outResetNeeded);
456     virtual void dumpSurface(std::string& dump);
457     virtual void configureVirtualKeys();
458     virtual void dumpVirtualKeys(std::string& dump);
459     virtual void parseCalibration();
460     virtual void resolveCalibration();
461     virtual void dumpCalibration(std::string& dump);
462     virtual void updateAffineTransformation();
463     virtual void dumpAffineTransformation(std::string& dump);
464     virtual void resolveExternalStylusPresence();
465     virtual bool hasStylus() const = 0;
466     virtual bool hasExternalStylus() const;
467 
468     virtual void syncTouch(nsecs_t when, RawState* outState) = 0;
469 
470 private:
471     // The current viewport.
472     // The components of the viewport are specified in the display's rotated orientation.
473     DisplayViewport mViewport;
474 
475     // The surface orientation, width and height set by configureSurface().
476     // The width and height are derived from the viewport but are specified
477     // in the natural orientation.
478     // The surface origin specifies how the surface coordinates should be translated
479     // to align with the logical display coordinate space.
480     int32_t mSurfaceWidth;
481     int32_t mSurfaceHeight;
482     int32_t mSurfaceLeft;
483     int32_t mSurfaceTop;
484 
485     // Similar to the surface coordinates, but in the raw display coordinate space rather than in
486     // the logical coordinate space.
487     int32_t mPhysicalWidth;
488     int32_t mPhysicalHeight;
489     int32_t mPhysicalLeft;
490     int32_t mPhysicalTop;
491 
492     // The orientation may be different from the viewport orientation as it specifies
493     // the rotation of the surface coordinates required to produce the viewport's
494     // requested orientation, so it will depend on whether the device is orientation aware.
495     int32_t mSurfaceOrientation;
496 
497     // Translation and scaling factors, orientation-independent.
498     float mXTranslate;
499     float mXScale;
500     float mXPrecision;
501 
502     float mYTranslate;
503     float mYScale;
504     float mYPrecision;
505 
506     float mGeometricScale;
507 
508     float mPressureScale;
509 
510     float mSizeScale;
511 
512     float mOrientationScale;
513 
514     float mDistanceScale;
515 
516     bool mHaveTilt;
517     float mTiltXCenter;
518     float mTiltXScale;
519     float mTiltYCenter;
520     float mTiltYScale;
521 
522     bool mExternalStylusConnected;
523 
524     // Oriented motion ranges for input device info.
525     struct OrientedRanges {
526         InputDeviceInfo::MotionRange x;
527         InputDeviceInfo::MotionRange y;
528         InputDeviceInfo::MotionRange pressure;
529 
530         bool haveSize;
531         InputDeviceInfo::MotionRange size;
532 
533         bool haveTouchSize;
534         InputDeviceInfo::MotionRange touchMajor;
535         InputDeviceInfo::MotionRange touchMinor;
536 
537         bool haveToolSize;
538         InputDeviceInfo::MotionRange toolMajor;
539         InputDeviceInfo::MotionRange toolMinor;
540 
541         bool haveOrientation;
542         InputDeviceInfo::MotionRange orientation;
543 
544         bool haveDistance;
545         InputDeviceInfo::MotionRange distance;
546 
547         bool haveTilt;
548         InputDeviceInfo::MotionRange tilt;
549 
OrientedRangesOrientedRanges550         OrientedRanges() { clear(); }
551 
clearOrientedRanges552         void clear() {
553             haveSize = false;
554             haveTouchSize = false;
555             haveToolSize = false;
556             haveOrientation = false;
557             haveDistance = false;
558             haveTilt = false;
559         }
560     } mOrientedRanges;
561 
562     // Oriented dimensions and precision.
563     float mOrientedXPrecision;
564     float mOrientedYPrecision;
565 
566     struct CurrentVirtualKeyState {
567         bool down;
568         bool ignored;
569         nsecs_t downTime;
570         int32_t keyCode;
571         int32_t scanCode;
572     } mCurrentVirtualKey;
573 
574     // Scale factor for gesture or mouse based pointer movements.
575     float mPointerXMovementScale;
576     float mPointerYMovementScale;
577 
578     // Scale factor for gesture based zooming and other freeform motions.
579     float mPointerXZoomScale;
580     float mPointerYZoomScale;
581 
582     // The maximum swipe width.
583     float mPointerGestureMaxSwipeWidth;
584 
585     struct PointerDistanceHeapElement {
586         uint32_t currentPointerIndex : 8;
587         uint32_t lastPointerIndex : 8;
588         uint64_t distance : 48; // squared distance
589     };
590 
591     enum PointerUsage {
592         POINTER_USAGE_NONE,
593         POINTER_USAGE_GESTURES,
594         POINTER_USAGE_STYLUS,
595         POINTER_USAGE_MOUSE,
596     };
597     PointerUsage mPointerUsage;
598 
599     struct PointerGesture {
600         enum Mode {
601             // No fingers, button is not pressed.
602             // Nothing happening.
603             NEUTRAL,
604 
605             // No fingers, button is not pressed.
606             // Tap detected.
607             // Emits DOWN and UP events at the pointer location.
608             TAP,
609 
610             // Exactly one finger dragging following a tap.
611             // Pointer follows the active finger.
612             // Emits DOWN, MOVE and UP events at the pointer location.
613             //
614             // Detect double-taps when the finger goes up while in TAP_DRAG mode.
615             TAP_DRAG,
616 
617             // Button is pressed.
618             // Pointer follows the active finger if there is one.  Other fingers are ignored.
619             // Emits DOWN, MOVE and UP events at the pointer location.
620             BUTTON_CLICK_OR_DRAG,
621 
622             // Exactly one finger, button is not pressed.
623             // Pointer follows the active finger.
624             // Emits HOVER_MOVE events at the pointer location.
625             //
626             // Detect taps when the finger goes up while in HOVER mode.
627             HOVER,
628 
629             // Exactly two fingers but neither have moved enough to clearly indicate
630             // whether a swipe or freeform gesture was intended.  We consider the
631             // pointer to be pressed so this enables clicking or long-pressing on buttons.
632             // Pointer does not move.
633             // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
634             PRESS,
635 
636             // Exactly two fingers moving in the same direction, button is not pressed.
637             // Pointer does not move.
638             // Emits DOWN, MOVE and UP events with a single pointer coordinate that
639             // follows the midpoint between both fingers.
640             SWIPE,
641 
642             // Two or more fingers moving in arbitrary directions, button is not pressed.
643             // Pointer does not move.
644             // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
645             // each finger individually relative to the initial centroid of the finger.
646             FREEFORM,
647 
648             // Waiting for quiet time to end before starting the next gesture.
649             QUIET,
650         };
651 
652         // Time the first finger went down.
653         nsecs_t firstTouchTime;
654 
655         // The active pointer id from the raw touch data.
656         int32_t activeTouchId; // -1 if none
657 
658         // The active pointer id from the gesture last delivered to the application.
659         int32_t activeGestureId; // -1 if none
660 
661         // Pointer coords and ids for the current and previous pointer gesture.
662         Mode currentGestureMode;
663         BitSet32 currentGestureIdBits;
664         uint32_t currentGestureIdToIndex[MAX_POINTER_ID + 1];
665         PointerProperties currentGestureProperties[MAX_POINTERS];
666         PointerCoords currentGestureCoords[MAX_POINTERS];
667 
668         Mode lastGestureMode;
669         BitSet32 lastGestureIdBits;
670         uint32_t lastGestureIdToIndex[MAX_POINTER_ID + 1];
671         PointerProperties lastGestureProperties[MAX_POINTERS];
672         PointerCoords lastGestureCoords[MAX_POINTERS];
673 
674         // Time the pointer gesture last went down.
675         nsecs_t downTime;
676 
677         // Time when the pointer went down for a TAP.
678         nsecs_t tapDownTime;
679 
680         // Time when the pointer went up for a TAP.
681         nsecs_t tapUpTime;
682 
683         // Location of initial tap.
684         float tapX, tapY;
685 
686         // Time we started waiting for quiescence.
687         nsecs_t quietTime;
688 
689         // Reference points for multitouch gestures.
690         float referenceTouchX; // reference touch X/Y coordinates in surface units
691         float referenceTouchY;
692         float referenceGestureX; // reference gesture X/Y coordinates in pixels
693         float referenceGestureY;
694 
695         // Distance that each pointer has traveled which has not yet been
696         // subsumed into the reference gesture position.
697         BitSet32 referenceIdBits;
698         struct Delta {
699             float dx, dy;
700         };
701         Delta referenceDeltas[MAX_POINTER_ID + 1];
702 
703         // Describes how touch ids are mapped to gesture ids for freeform gestures.
704         uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
705 
706         // A velocity tracker for determining whether to switch active pointers during drags.
707         VelocityTracker velocityTracker;
708 
resetPointerGesture709         void reset() {
710             firstTouchTime = LLONG_MIN;
711             activeTouchId = -1;
712             activeGestureId = -1;
713             currentGestureMode = NEUTRAL;
714             currentGestureIdBits.clear();
715             lastGestureMode = NEUTRAL;
716             lastGestureIdBits.clear();
717             downTime = 0;
718             velocityTracker.clear();
719             resetTap();
720             resetQuietTime();
721         }
722 
resetTapPointerGesture723         void resetTap() {
724             tapDownTime = LLONG_MIN;
725             tapUpTime = LLONG_MIN;
726         }
727 
resetQuietTimePointerGesture728         void resetQuietTime() { quietTime = LLONG_MIN; }
729     } mPointerGesture;
730 
731     struct PointerSimple {
732         PointerCoords currentCoords;
733         PointerProperties currentProperties;
734         PointerCoords lastCoords;
735         PointerProperties lastProperties;
736 
737         // True if the pointer is down.
738         bool down;
739 
740         // True if the pointer is hovering.
741         bool hovering;
742 
743         // Time the pointer last went down.
744         nsecs_t downTime;
745 
resetPointerSimple746         void reset() {
747             currentCoords.clear();
748             currentProperties.clear();
749             lastCoords.clear();
750             lastProperties.clear();
751             down = false;
752             hovering = false;
753             downTime = 0;
754         }
755     } mPointerSimple;
756 
757     // The pointer and scroll velocity controls.
758     VelocityControl mPointerVelocityControl;
759     VelocityControl mWheelXVelocityControl;
760     VelocityControl mWheelYVelocityControl;
761 
762     // Latency statistics for touch events
763     struct LatencyStatistics mStatistics;
764 
765     std::optional<DisplayViewport> findViewport();
766 
767     void resetExternalStylus();
768     void clearStylusDataPendingFlags();
769 
770     void sync(nsecs_t when);
771 
772     bool consumeRawTouches(nsecs_t when, uint32_t policyFlags);
773     void processRawTouches(bool timeout);
774     void cookAndDispatch(nsecs_t when);
775     void dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, int32_t keyEventAction,
776                             int32_t keyEventFlags);
777 
778     void dispatchTouches(nsecs_t when, uint32_t policyFlags);
779     void dispatchHoverExit(nsecs_t when, uint32_t policyFlags);
780     void dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags);
781     void dispatchButtonRelease(nsecs_t when, uint32_t policyFlags);
782     void dispatchButtonPress(nsecs_t when, uint32_t policyFlags);
783     const BitSet32& findActiveIdBits(const CookedPointerData& cookedPointerData);
784     void cookPointerData();
785     void abortTouches(nsecs_t when, uint32_t policyFlags);
786 
787     void dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage);
788     void abortPointerUsage(nsecs_t when, uint32_t policyFlags);
789 
790     void dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout);
791     void abortPointerGestures(nsecs_t when, uint32_t policyFlags);
792     bool preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
793                                 bool* outFinishPreviousGesture, bool isTimeout);
794 
795     void dispatchPointerStylus(nsecs_t when, uint32_t policyFlags);
796     void abortPointerStylus(nsecs_t when, uint32_t policyFlags);
797 
798     void dispatchPointerMouse(nsecs_t when, uint32_t policyFlags);
799     void abortPointerMouse(nsecs_t when, uint32_t policyFlags);
800 
801     void dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering);
802     void abortPointerSimple(nsecs_t when, uint32_t policyFlags);
803 
804     bool assignExternalStylusId(const RawState& state, bool timeout);
805     void applyExternalStylusButtonState(nsecs_t when);
806     void applyExternalStylusTouchState(nsecs_t when);
807 
808     // Dispatches a motion event.
809     // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
810     // method will take care of setting the index and transmuting the action to DOWN or UP
811     // it is the first / last pointer to go down / up.
812     void dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, int32_t action,
813                         int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
814                         int32_t edgeFlags, uint32_t deviceTimestamp,
815                         const PointerProperties* properties, const PointerCoords* coords,
816                         const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
817                         float xPrecision, float yPrecision, nsecs_t downTime);
818 
819     // Updates pointer coords and properties for pointers with specified ids that have moved.
820     // Returns true if any of them changed.
821     bool updateMovedPointers(const PointerProperties* inProperties, const PointerCoords* inCoords,
822                              const uint32_t* inIdToIndex, PointerProperties* outProperties,
823                              PointerCoords* outCoords, const uint32_t* outIdToIndex,
824                              BitSet32 idBits) const;
825 
826     bool isPointInsideSurface(int32_t x, int32_t y);
827     const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
828 
829     static void assignPointerIds(const RawState* last, RawState* current);
830 
831     void reportEventForStatistics(nsecs_t evdevTime);
832 
833     const char* modeToString(DeviceMode deviceMode);
834 };
835 
836 } // namespace android
837 
838 #endif // _UI_INPUTREADER_TOUCH_INPUT_MAPPER_H
839