• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #pragma once
18 
19 #include <array>
20 #include <climits>
21 #include <limits>
22 #include <list>
23 #include <memory>
24 #include <optional>
25 #include <string>
26 #include <utility>
27 #include <vector>
28 
29 #include <input/DisplayViewport.h>
30 #include <input/Input.h>
31 #include <input/InputDevice.h>
32 #include <input/VelocityControl.h>
33 #include <input/VelocityTracker.h>
34 #include <stdint.h>
35 #include <ui/Rect.h>
36 #include <ui/Rotation.h>
37 #include <ui/Size.h>
38 #include <ui/Transform.h>
39 #include <utils/BitSet.h>
40 #include <utils/Timers.h>
41 
42 #include "CursorButtonAccumulator.h"
43 #include "CursorScrollAccumulator.h"
44 #include "EventHub.h"
45 #include "InputMapper.h"
46 #include "InputReaderBase.h"
47 #include "NotifyArgs.h"
48 #include "StylusState.h"
49 #include "TouchButtonAccumulator.h"
50 
51 namespace android {
52 
53 // Maximum amount of latency to add to touch events while waiting for data from an
54 // external stylus.
55 static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
56 
57 // Maximum amount of time to wait on touch data before pushing out new pressure data.
58 static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
59 
60 /* Raw axis information from the driver. */
61 struct RawPointerAxes {
62     RawAbsoluteAxisInfo x{};
63     RawAbsoluteAxisInfo y{};
64     std::optional<RawAbsoluteAxisInfo> pressure{};
65     std::optional<RawAbsoluteAxisInfo> touchMajor{};
66     std::optional<RawAbsoluteAxisInfo> touchMinor{};
67     std::optional<RawAbsoluteAxisInfo> toolMajor{};
68     std::optional<RawAbsoluteAxisInfo> toolMinor{};
69     std::optional<RawAbsoluteAxisInfo> orientation{};
70     std::optional<RawAbsoluteAxisInfo> distance{};
71     std::optional<RawAbsoluteAxisInfo> tiltX{};
72     std::optional<RawAbsoluteAxisInfo> tiltY{};
73     std::optional<RawAbsoluteAxisInfo> trackingId{};
74     std::optional<RawAbsoluteAxisInfo> slot{};
75 
getRawWidthRawPointerAxes76     inline int32_t getRawWidth() const { return x.maxValue - x.minValue + 1; }
getRawHeightRawPointerAxes77     inline int32_t getRawHeight() const { return y.maxValue - y.minValue + 1; }
clearRawPointerAxes78     inline void clear() { *this = RawPointerAxes(); }
79 };
80 
81 using PropertiesArray = std::array<PointerProperties, MAX_POINTERS>;
82 using CoordsArray = std::array<PointerCoords, MAX_POINTERS>;
83 using IdToIndexArray = std::array<uint32_t, MAX_POINTER_ID + 1>;
84 
85 /* Raw data for a collection of pointers including a pointer id mapping table. */
86 struct RawPointerData {
87     struct Pointer {
88         uint32_t id{0xFFFFFFFF};
89         int32_t x{};
90         int32_t y{};
91         int32_t pressure{};
92         int32_t touchMajor{};
93         int32_t touchMinor{};
94         int32_t toolMajor{};
95         int32_t toolMinor{};
96         int32_t orientation{};
97         int32_t distance{};
98         int32_t tiltX{};
99         int32_t tiltY{};
100         // A fully decoded ToolType constant.
101         ToolType toolType{ToolType::UNKNOWN};
102         bool isHovering{false};
103     };
104 
105     uint32_t pointerCount{};
106     std::array<Pointer, MAX_POINTERS> pointers{};
107     BitSet32 hoveringIdBits{}, touchingIdBits{}, canceledIdBits{};
108     IdToIndexArray idToIndex{};
109 
clearRawPointerData110     inline void clear() { *this = RawPointerData(); }
111 
112     void getCentroidOfTouchingPointers(float* outX, float* outY) const;
113 
markIdBitRawPointerData114     inline void markIdBit(uint32_t id, bool isHovering) {
115         if (isHovering) {
116             hoveringIdBits.markBit(id);
117         } else {
118             touchingIdBits.markBit(id);
119         }
120     }
121 
clearIdBitsRawPointerData122     inline void clearIdBits() {
123         hoveringIdBits.clear();
124         touchingIdBits.clear();
125         canceledIdBits.clear();
126     }
127 
pointerForIdRawPointerData128     inline const Pointer& pointerForId(uint32_t id) const { return pointers[idToIndex[id]]; }
129 
isHoveringRawPointerData130     inline bool isHovering(uint32_t pointerIndex) { return pointers[pointerIndex].isHovering; }
131 };
132 
133 /* Cooked data for a collection of pointers including a pointer id mapping table. */
134 struct CookedPointerData {
135     uint32_t pointerCount{};
136     PropertiesArray pointerProperties{};
137     CoordsArray pointerCoords{};
138     BitSet32 hoveringIdBits{}, touchingIdBits{}, canceledIdBits{}, validIdBits{};
139     IdToIndexArray idToIndex{};
140 
clearCookedPointerData141     inline void clear() { *this = CookedPointerData(); }
142 
pointerCoordsForIdCookedPointerData143     inline const PointerCoords& pointerCoordsForId(uint32_t id) const {
144         return pointerCoords[idToIndex[id]];
145     }
146 
editPointerCoordsWithIdCookedPointerData147     inline PointerCoords& editPointerCoordsWithId(uint32_t id) {
148         return pointerCoords[idToIndex[id]];
149     }
150 
editPointerPropertiesWithIdCookedPointerData151     inline PointerProperties& editPointerPropertiesWithId(uint32_t id) {
152         return pointerProperties[idToIndex[id]];
153     }
154 
isHoveringCookedPointerData155     inline bool isHovering(uint32_t pointerIndex) const {
156         return hoveringIdBits.hasBit(pointerProperties[pointerIndex].id);
157     }
158 
isTouchingCookedPointerData159     inline bool isTouching(uint32_t pointerIndex) const {
160         return touchingIdBits.hasBit(pointerProperties[pointerIndex].id);
161     }
162 
hasPointerCoordsForIdCookedPointerData163     inline bool hasPointerCoordsForId(uint32_t id) const { return validIdBits.hasBit(id); }
164 };
165 
166 class TouchInputMapper : public InputMapper {
167 public:
168     ~TouchInputMapper() override;
169 
170     uint32_t getSources() const override;
171     void populateDeviceInfo(InputDeviceInfo& deviceInfo) override;
172     void dump(std::string& dump) override;
173     [[nodiscard]] std::list<NotifyArgs> reconfigure(nsecs_t when,
174                                                     const InputReaderConfiguration& config,
175                                                     ConfigurationChanges changes) override;
176     [[nodiscard]] std::list<NotifyArgs> reset(nsecs_t when) override;
177     [[nodiscard]] std::list<NotifyArgs> process(const RawEvent& rawEvent) override;
178 
179     int32_t getKeyCodeState(uint32_t sourceMask, int32_t keyCode) override;
180     int32_t getScanCodeState(uint32_t sourceMask, int32_t scanCode) override;
181     bool markSupportedKeyCodes(uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
182                                uint8_t* outFlags) override;
183 
184     [[nodiscard]] std::list<NotifyArgs> cancelTouch(nsecs_t when, nsecs_t readTime) override;
185     [[nodiscard]] std::list<NotifyArgs> timeoutExpired(nsecs_t when) override;
186     [[nodiscard]] std::list<NotifyArgs> updateExternalStylusState(
187             const StylusState& state) override;
188     std::optional<ui::LogicalDisplayId> getAssociatedDisplayId() const override;
189 
190 protected:
191     CursorButtonAccumulator mCursorButtonAccumulator;
192     CursorScrollAccumulator mCursorScrollAccumulator;
193     TouchButtonAccumulator mTouchButtonAccumulator;
194 
195     struct VirtualKey {
196         int32_t keyCode;
197         int32_t scanCode;
198         uint32_t flags;
199 
200         // computed hit box, specified in touch screen coords based on known display size
201         int32_t hitLeft;
202         int32_t hitTop;
203         int32_t hitRight;
204         int32_t hitBottom;
205 
isHitVirtualKey206         inline bool isHit(int32_t x, int32_t y) const {
207             return x >= hitLeft && x <= hitRight && y >= hitTop && y <= hitBottom;
208         }
209     };
210 
211     // Input sources and device mode.
212     uint32_t mSource{0};
213 
214     enum class DeviceMode {
215         DISABLED,   // input is disabled
216         DIRECT,     // direct mapping (touchscreen)
217         NAVIGATION, // unscaled mapping with assist gesture (touch navigation)
218         POINTER,    // pointer mapping (e.g. absolute mouse, drawing tablet)
219 
220         ftl_last = POINTER
221     };
222     DeviceMode mDeviceMode{DeviceMode::DISABLED};
223 
224     // The reader's configuration.
225     InputReaderConfiguration mConfig;
226 
227     // Immutable configuration parameters.
228     struct Parameters {
229         enum class DeviceType {
230             TOUCH_SCREEN,
231             TOUCH_NAVIGATION,
232             POINTER,
233 
234             ftl_last = POINTER
235         };
236 
237         // TouchInputMapper will configure devices with INPUT_PROP_DIRECT as
238         // DeviceType::TOUCH_SCREEN, and will otherwise use DeviceType::POINTER by default.
239         // This can be overridden by IDC files, using the `touch.deviceType` config.
240         DeviceType deviceType;
241         bool hasAssociatedDisplay = false;
242         bool associatedDisplayIsExternal;
243         bool orientationAware;
244 
245         ui::Rotation orientation;
246 
247         bool hasButtonUnderPad;
248         std::string uniqueDisplayId;
249 
250         enum class GestureMode {
251             SINGLE_TOUCH,
252             MULTI_TOUCH,
253 
254             ftl_last = MULTI_TOUCH
255         };
256         GestureMode gestureMode;
257 
258         bool wake;
259 
260         // The Universal Stylus Initiative (USI) protocol version supported by this device.
261         std::optional<InputDeviceUsiVersion> usiVersion;
262 
263         // Allows touches while the display is off.
264         bool enableForInactiveViewport;
265     } mParameters;
266 
267     // Immutable calibration parameters in parsed form.
268     struct Calibration {
269         // Size
270         enum class SizeCalibration {
271             DEFAULT,
272             NONE,
273             GEOMETRIC,
274             DIAMETER,
275             BOX,
276             AREA,
277             ftl_last = AREA
278         };
279 
280         SizeCalibration sizeCalibration;
281 
282         std::optional<float> sizeScale;
283         std::optional<float> sizeBias;
284         std::optional<bool> sizeIsSummed;
285 
286         // Pressure
287         enum class PressureCalibration {
288             DEFAULT,
289             NONE,
290             PHYSICAL,
291             AMPLITUDE,
292         };
293 
294         PressureCalibration pressureCalibration;
295         std::optional<float> pressureScale;
296 
297         // Orientation
298         enum class OrientationCalibration {
299             DEFAULT,
300             NONE,
301             INTERPOLATED,
302             VECTOR,
303         };
304 
305         OrientationCalibration orientationCalibration;
306 
307         // Distance
308         enum class DistanceCalibration {
309             DEFAULT,
310             NONE,
311             SCALED,
312         };
313 
314         DistanceCalibration distanceCalibration;
315         std::optional<float> distanceScale;
316 
applySizeScaleAndBiasCalibration317         inline void applySizeScaleAndBias(float& outSize) const {
318             if (sizeScale) {
319                 outSize *= *sizeScale;
320             }
321             if (sizeBias) {
322                 outSize += *sizeBias;
323             }
324             if (outSize < 0) {
325                 outSize = 0;
326             }
327         }
328     } mCalibration;
329 
330     // Affine location transformation/calibration
331     struct TouchAffineTransformation mAffineTransform;
332 
333     RawPointerAxes mRawPointerAxes;
334 
335     struct RawState {
336         nsecs_t when{std::numeric_limits<nsecs_t>::min()};
337         nsecs_t readTime{};
338 
339         // Raw pointer sample data.
340         RawPointerData rawPointerData{};
341 
342         int32_t buttonState{};
343 
344         // Scroll state.
345         float rawVScroll{};
346         float rawHScroll{};
347 
clearRawState348         inline void clear() { *this = RawState(); }
349     };
350 
351     friend std::ostream& operator<<(std::ostream& out, const RawState& state);
352 
353     struct CookedState {
354         // Cooked pointer sample data.
355         CookedPointerData cookedPointerData{};
356 
357         // Id bits used to differentiate fingers, stylus and mouse tools.
358         BitSet32 fingerIdBits{};
359         BitSet32 stylusIdBits{};
360         BitSet32 mouseIdBits{};
361 
362         int32_t buttonState{};
363 
clearCookedState364         inline void clear() { *this = CookedState(); }
365     };
366 
367     std::vector<RawState> mRawStatesPending;
368     RawState mCurrentRawState;
369     CookedState mCurrentCookedState;
370     RawState mLastRawState;
371     CookedState mLastCookedState;
372 
373     enum class ExternalStylusPresence {
374         // No external stylus connected.
375         NONE,
376         // An external stylus that can report touch/pressure that can be fused with the touchscreen.
377         TOUCH_FUSION,
378         // An external stylus that can only report buttons.
379         BUTTON_FUSION,
380         ftl_last = BUTTON_FUSION,
381     };
382     ExternalStylusPresence mExternalStylusPresence{ExternalStylusPresence::NONE};
383     // State provided by an external stylus
384     StylusState mExternalStylusState;
385     // If an external stylus is capable of reporting pointer-specific data like pressure, we will
386     // attempt to fuse the pointer data reported by the stylus to the first touch pointer. This is
387     // the id of the pointer to which the external stylus data is fused.
388     std::optional<uint32_t> mFusedStylusPointerId;
389     nsecs_t mExternalStylusFusionTimeout;
390     bool mExternalStylusDataPending;
391     // A subset of the buttons in mCurrentRawState that came from an external stylus.
392     int32_t mExternalStylusButtonsApplied{0};
393     // True if the current cooked pointer data was modified due to the state of an external stylus.
394     bool mCurrentStreamModifiedByExternalStylus{false};
395 
396     // True if we sent a HOVER_ENTER event.
397     bool mSentHoverEnter{false};
398 
399     // Have we assigned pointer IDs for this stream
400     bool mHavePointerIds{false};
401 
402     // Is the current stream of direct touch events aborted
403     bool mCurrentMotionAborted{false};
404 
405     // The time the primary pointer last went down.
406     nsecs_t mDownTime{0};
407 
408     std::vector<VirtualKey> mVirtualKeys;
409 
410     explicit TouchInputMapper(InputDeviceContext& deviceContext,
411                               const InputReaderConfiguration& readerConfig);
412 
413     virtual void dumpParameters(std::string& dump);
414     virtual void configureRawPointerAxes();
415     virtual void dumpRawPointerAxes(std::string& dump);
416     virtual void configureInputDevice(nsecs_t when, bool* outResetNeeded);
417     virtual void dumpDisplay(std::string& dump);
418     virtual void configureVirtualKeys();
419     virtual void dumpVirtualKeys(std::string& dump);
420     virtual void parseCalibration();
421     virtual void resolveCalibration();
422     virtual void dumpCalibration(std::string& dump);
423     virtual void updateAffineTransformation();
424     virtual void dumpAffineTransformation(std::string& dump);
425     virtual void resolveExternalStylusPresence();
426     virtual bool hasStylus() const = 0;
427     virtual bool hasExternalStylus() const;
428 
429     virtual void syncTouch(nsecs_t when, RawState* outState) = 0;
430 
431 private:
432     // The current viewport.
433     // The components of the viewport are specified in the display's rotated orientation.
434     DisplayViewport mViewport;
435 
436     // We refer to the display as being in the "natural orientation" when there is no rotation
437     // applied. The display size obtained from the viewport in the natural orientation.
438     // Always starts at (0, 0).
439     ui::Size mDisplayBounds{ui::kInvalidSize};
440 
441     // The physical frame is the rectangle in the rotated display's coordinate space that maps to
442     // the logical display frame.
443     Rect mPhysicalFrameInRotatedDisplay{Rect::INVALID_RECT};
444 
445     // The orientation of the input device relative to that of the display panel. It specifies
446     // the rotation of the input device coordinates required to produce the display panel
447     // orientation, so it will depend on whether the device is orientation aware.
448     ui::Rotation mInputDeviceOrientation{ui::ROTATION_0};
449 
450     // The transform that maps the input device's raw coordinate space to the un-rotated display's
451     // coordinate space. InputReader generates events in the un-rotated display's coordinate space.
452     ui::Transform mRawToDisplay;
453 
454     // The transform that maps the input device's raw coordinate space to the rotated display's
455     // coordinate space. This used to perform hit-testing of raw events with the physical frame in
456     // the rotated coordinate space. See mPhysicalFrameInRotatedDisplay.
457     ui::Transform mRawToRotatedDisplay;
458 
459     // The transform used for non-planar raw axes, such as orientation and tilt.
460     ui::Transform mRawRotation;
461 
462     float mGeometricScale;
463 
464     float mPressureScale;
465 
466     float mSizeScale;
467 
468     float mOrientationScale;
469 
470     float mDistanceScale;
471 
472     bool mHaveTilt;
473     float mTiltXCenter;
474     float mTiltXScale;
475     float mTiltYCenter;
476     float mTiltYScale;
477 
478     // Oriented motion ranges for input device info.
479     struct OrientedRanges {
480         InputDeviceInfo::MotionRange x;
481         InputDeviceInfo::MotionRange y;
482         InputDeviceInfo::MotionRange pressure;
483 
484         std::optional<InputDeviceInfo::MotionRange> size;
485 
486         std::optional<InputDeviceInfo::MotionRange> touchMajor;
487         std::optional<InputDeviceInfo::MotionRange> touchMinor;
488 
489         std::optional<InputDeviceInfo::MotionRange> toolMajor;
490         std::optional<InputDeviceInfo::MotionRange> toolMinor;
491 
492         std::optional<InputDeviceInfo::MotionRange> orientation;
493 
494         std::optional<InputDeviceInfo::MotionRange> distance;
495 
496         std::optional<InputDeviceInfo::MotionRange> tilt;
497 
clearOrientedRanges498         void clear() {
499             size = std::nullopt;
500             touchMajor = std::nullopt;
501             touchMinor = std::nullopt;
502             toolMajor = std::nullopt;
503             toolMinor = std::nullopt;
504             orientation = std::nullopt;
505             distance = std::nullopt;
506             tilt = std::nullopt;
507         }
508     } mOrientedRanges;
509 
510     // Oriented dimensions and precision.
511     float mOrientedXPrecision;
512     float mOrientedYPrecision;
513 
514     struct CurrentVirtualKeyState {
515         bool down;
516         bool ignored;
517         nsecs_t downTime;
518         int32_t keyCode;
519         int32_t scanCode;
520     } mCurrentVirtualKey;
521 
522     // Scale factor for gesture or mouse based pointer movements.
523     float mPointerXMovementScale;
524     float mPointerYMovementScale;
525 
526     // Scale factor for gesture based zooming and other freeform motions.
527     float mPointerXZoomScale;
528     float mPointerYZoomScale;
529 
530     // The maximum swipe width between pointers to detect a swipe gesture
531     // in the number of pixels.Touches that are wider than this are translated
532     // into freeform gestures.
533     float mPointerGestureMaxSwipeWidth;
534 
535     struct PointerDistanceHeapElement {
536         uint32_t currentPointerIndex : 8 {};
537         uint32_t lastPointerIndex : 8 {};
538         uint64_t distance : 48 {}; // squared distance
539     };
540 
541     enum class PointerUsage {
542         NONE,
543         GESTURES,
544         STYLUS,
545         MOUSE,
546     };
547     PointerUsage mPointerUsage{PointerUsage::NONE};
548 
549     struct PointerGesture {
550         enum class Mode {
551             // No fingers, button is not pressed.
552             // Nothing happening.
553             NEUTRAL,
554 
555             // No fingers, button is not pressed.
556             // Tap detected.
557             // Emits DOWN and UP events at the pointer location.
558             TAP,
559 
560             // Exactly one finger dragging following a tap.
561             // Pointer follows the active finger.
562             // Emits DOWN, MOVE and UP events at the pointer location.
563             //
564             // Detect double-taps when the finger goes up while in TAP_DRAG mode.
565             TAP_DRAG,
566 
567             // Button is pressed.
568             // Pointer follows the active finger if there is one.  Other fingers are ignored.
569             // Emits DOWN, MOVE and UP events at the pointer location.
570             BUTTON_CLICK_OR_DRAG,
571 
572             // Exactly one finger, button is not pressed.
573             // Pointer follows the active finger.
574             // Emits HOVER_MOVE events at the pointer location.
575             //
576             // Detect taps when the finger goes up while in HOVER mode.
577             HOVER,
578 
579             // Exactly two fingers but neither have moved enough to clearly indicate
580             // whether a swipe or freeform gesture was intended.  We consider the
581             // pointer to be pressed so this enables clicking or long-pressing on buttons.
582             // Pointer does not move.
583             // Emits DOWN, MOVE and UP events with a single stationary pointer coordinate.
584             PRESS,
585 
586             // Exactly two fingers moving in the same direction, button is not pressed.
587             // Pointer does not move.
588             // Emits DOWN, MOVE and UP events with a single pointer coordinate that
589             // follows the midpoint between both fingers.
590             SWIPE,
591 
592             // Two or more fingers moving in arbitrary directions, button is not pressed.
593             // Pointer does not move.
594             // Emits DOWN, POINTER_DOWN, MOVE, POINTER_UP and UP events that follow
595             // each finger individually relative to the initial centroid of the finger.
596             FREEFORM,
597 
598             // Waiting for quiet time to end before starting the next gesture.
599             QUIET,
600 
601             ftl_last = QUIET,
602         };
603 
604         // When a gesture is sent to an unfocused window, return true if it can bring that window
605         // into focus, false otherwise.
canGestureAffectWindowFocusPointerGesture606         static bool canGestureAffectWindowFocus(Mode mode) {
607             switch (mode) {
608                 case Mode::TAP:
609                 case Mode::TAP_DRAG:
610                 case Mode::BUTTON_CLICK_OR_DRAG:
611                     // Taps can affect window focus.
612                     return true;
613                 case Mode::FREEFORM:
614                 case Mode::HOVER:
615                 case Mode::NEUTRAL:
616                 case Mode::PRESS:
617                 case Mode::QUIET:
618                 case Mode::SWIPE:
619                     // Most gestures can be performed on an unfocused window, so they should not
620                     // not affect window focus.
621                     return false;
622             }
623         }
624 
625         // Time the first finger went down.
626         nsecs_t firstTouchTime;
627 
628         // The active pointer id from the raw touch data.
629         int32_t activeTouchId; // -1 if none
630 
631         // The active pointer id from the gesture last delivered to the application.
632         int32_t activeGestureId; // -1 if none
633 
634         // Pointer coords and ids for the current and previous pointer gesture.
635         Mode currentGestureMode;
636         BitSet32 currentGestureIdBits;
637         IdToIndexArray currentGestureIdToIndex{};
638         PropertiesArray currentGestureProperties{};
639         CoordsArray currentGestureCoords{};
640 
641         Mode lastGestureMode;
642         BitSet32 lastGestureIdBits;
643         IdToIndexArray lastGestureIdToIndex{};
644         PropertiesArray lastGestureProperties{};
645         CoordsArray lastGestureCoords{};
646 
647         // Time the pointer gesture last went down.
648         nsecs_t downTime;
649 
650         // Time when the pointer went down for a TAP.
651         nsecs_t tapDownTime;
652 
653         // Time when the pointer went up for a TAP.
654         nsecs_t tapUpTime;
655 
656         // Location of initial tap.
657         float tapX, tapY;
658 
659         // Time we started waiting for quiescence.
660         nsecs_t quietTime;
661 
662         // Reference points for multitouch gestures.
663         float referenceTouchX; // reference touch X/Y coordinates in surface units
664         float referenceTouchY;
665         float referenceGestureX; // reference gesture X/Y coordinates in pixels
666         float referenceGestureY;
667 
668         // Distance that each pointer has traveled which has not yet been
669         // subsumed into the reference gesture position.
670         BitSet32 referenceIdBits;
671         struct Delta {
672             float dx, dy;
673         };
674         Delta referenceDeltas[MAX_POINTER_ID + 1];
675 
676         // Describes how touch ids are mapped to gesture ids for freeform gestures.
677         uint32_t freeformTouchToGestureIdMap[MAX_POINTER_ID + 1];
678 
679         // A velocity tracker for determining whether to switch active pointers during drags.
680         VelocityTracker velocityTracker;
681 
resetPointerGesture682         void reset() {
683             firstTouchTime = LLONG_MIN;
684             activeTouchId = -1;
685             activeGestureId = -1;
686             currentGestureMode = Mode::NEUTRAL;
687             currentGestureIdBits.clear();
688             lastGestureMode = Mode::NEUTRAL;
689             lastGestureIdBits.clear();
690             downTime = 0;
691             velocityTracker.clear();
692             resetTap();
693             resetQuietTime();
694         }
695 
resetTapPointerGesture696         void resetTap() {
697             tapDownTime = LLONG_MIN;
698             tapUpTime = LLONG_MIN;
699         }
700 
resetQuietTimePointerGesture701         void resetQuietTime() { quietTime = LLONG_MIN; }
702     } mPointerGesture;
703 
704     struct PointerSimple {
705         PointerCoords currentCoords;
706         PointerProperties currentProperties;
707         PointerCoords lastCoords;
708         PointerProperties lastProperties;
709 
710         // True if the pointer is down.
711         bool down;
712 
713         // True if the pointer is hovering.
714         bool hovering;
715 
716         // Time the pointer last went down.
717         nsecs_t downTime;
718 
719         // Values reported for the last pointer event.
720         uint32_t source;
721         ui::LogicalDisplayId displayId{ui::LogicalDisplayId::INVALID};
722         float lastCursorX;
723         float lastCursorY;
724 
resetPointerSimple725         void reset() {
726             currentCoords.clear();
727             currentProperties.clear();
728             lastCoords.clear();
729             lastProperties.clear();
730             down = false;
731             hovering = false;
732             downTime = 0;
733             source = 0;
734             displayId = ui::LogicalDisplayId::INVALID;
735             lastCursorX = 0.f;
736             lastCursorY = 0.f;
737         }
738     } mPointerSimple;
739 
740     // The pointer and scroll velocity controls.
741     SimpleVelocityControl mPointerVelocityControl;
742     SimpleVelocityControl mWheelXVelocityControl;
743     SimpleVelocityControl mWheelYVelocityControl;
744 
745     std::optional<DisplayViewport> findViewport();
746 
747     void resetExternalStylus();
748     void clearStylusDataPendingFlags();
749 
750     int32_t clampResolution(const char* axisName, int32_t resolution) const;
751     void initializeOrientedRanges();
752     void initializeSizeRanges();
753 
754     [[nodiscard]] std::list<NotifyArgs> sync(nsecs_t when, nsecs_t readTime);
755 
756     [[nodiscard]] std::list<NotifyArgs> consumeRawTouches(nsecs_t when, nsecs_t readTime,
757                                                           uint32_t policyFlags, bool& outConsumed);
758     [[nodiscard]] std::list<NotifyArgs> processRawTouches(bool timeout);
759     [[nodiscard]] std::list<NotifyArgs> cookAndDispatch(nsecs_t when, nsecs_t readTime);
760     [[nodiscard]] NotifyKeyArgs dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
761                                                    uint32_t policyFlags, int32_t keyEventAction,
762                                                    int32_t keyEventFlags);
763 
764     [[nodiscard]] std::list<NotifyArgs> dispatchTouches(nsecs_t when, nsecs_t readTime,
765                                                         uint32_t policyFlags);
766     [[nodiscard]] std::list<NotifyArgs> dispatchHoverExit(nsecs_t when, nsecs_t readTime,
767                                                           uint32_t policyFlags);
768     [[nodiscard]] std::list<NotifyArgs> dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
769                                                                   uint32_t policyFlags);
770     [[nodiscard]] std::list<NotifyArgs> dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
771                                                               uint32_t policyFlags);
772     [[nodiscard]] std::list<NotifyArgs> dispatchButtonPress(nsecs_t when, nsecs_t readTime,
773                                                             uint32_t policyFlags);
774     [[nodiscard]] std::list<NotifyArgs> dispatchGestureButtonPress(nsecs_t when,
775                                                                    uint32_t policyFlags,
776                                                                    BitSet32 idBits,
777                                                                    nsecs_t readTime);
778     [[nodiscard]] std::list<NotifyArgs> dispatchGestureButtonRelease(nsecs_t when,
779                                                                      uint32_t policyFlags,
780                                                                      BitSet32 idBits,
781                                                                      nsecs_t readTime);
782     const BitSet32& findActiveIdBits(const CookedPointerData& cookedPointerData);
783     void cookPointerData();
784     [[nodiscard]] std::list<NotifyArgs> abortTouches(
785             nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
786             std::optional<ui::LogicalDisplayId> gestureDisplayId);
787 
788     [[nodiscard]] std::list<NotifyArgs> dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
789                                                              uint32_t policyFlags,
790                                                              PointerUsage pointerUsage);
791     [[nodiscard]] std::list<NotifyArgs> abortPointerUsage(nsecs_t when, nsecs_t readTime,
792                                                           uint32_t policyFlags);
793 
794     [[nodiscard]] std::list<NotifyArgs> dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
795                                                                 uint32_t policyFlags,
796                                                                 bool isTimeout);
797     [[nodiscard]] std::list<NotifyArgs> abortPointerGestures(nsecs_t when, nsecs_t readTime,
798                                                              uint32_t policyFlags);
799     bool preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
800                                 bool* outFinishPreviousGesture, bool isTimeout);
801 
802     // Returns true if we're in a period of "quiet time" when touchpad gestures should be ignored.
803     bool checkForTouchpadQuietTime(nsecs_t when);
804 
805     std::pair<int32_t, float> getFastestFinger();
806 
807     void prepareMultiFingerPointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
808                                            bool* outFinishPreviousGesture);
809 
810     // Moves the on-screen mouse pointer based on the movement of the pointer of the given ID
811     // between the last and current events. Uses a relative motion.
812     void moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId);
813 
814     [[nodiscard]] std::list<NotifyArgs> dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
815                                                               uint32_t policyFlags);
816     [[nodiscard]] std::list<NotifyArgs> abortPointerStylus(nsecs_t when, nsecs_t readTime,
817                                                            uint32_t policyFlags);
818 
819     [[nodiscard]] std::list<NotifyArgs> dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
820                                                              uint32_t policyFlags);
821     [[nodiscard]] std::list<NotifyArgs> abortPointerMouse(nsecs_t when, nsecs_t readTime,
822                                                           uint32_t policyFlags);
823 
824     [[nodiscard]] std::list<NotifyArgs> dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
825                                                               uint32_t policyFlags, bool down,
826                                                               bool hovering,
827                                                               ui::LogicalDisplayId displayId);
828     [[nodiscard]] std::list<NotifyArgs> abortPointerSimple(nsecs_t when, nsecs_t readTime,
829                                                            uint32_t policyFlags);
830 
831     // Attempts to assign a pointer id to the external stylus. Returns true if the state should be
832     // withheld from further processing while waiting for data from the stylus.
833     bool assignExternalStylusId(const RawState& state, bool timeout);
834     void applyExternalStylusButtonState(nsecs_t when);
835     void applyExternalStylusTouchState(nsecs_t when);
836 
837     // Dispatches a motion event.
838     // If the changedId is >= 0 and the action is POINTER_DOWN or POINTER_UP, the
839     // method will take care of setting the index and transmuting the action to DOWN or UP
840     // it is the first / last pointer to go down / up.
841     [[nodiscard]] NotifyMotionArgs dispatchMotion(
842             nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source,
843             ui::LogicalDisplayId displayId, int32_t action, int32_t actionButton, int32_t flags,
844             int32_t metaState, int32_t buttonState, int32_t edgeFlags,
845             const PropertiesArray& properties, const CoordsArray& coords,
846             const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
847             float yPrecision, nsecs_t downTime, MotionClassification classification) const;
848 
849     // Returns if this touch device is a touch screen with an associated display.
850     bool isTouchScreen();
851 
852     ui::LogicalDisplayId resolveDisplayId() const;
853 
854     bool isPointInsidePhysicalFrame(int32_t x, int32_t y) const;
855     const VirtualKey* findVirtualKeyHit(int32_t x, int32_t y);
856 
857     static void assignPointerIds(const RawState& last, RawState& current);
858 
859     // Compute input transforms for DIRECT and POINTER modes.
860     void computeInputTransforms();
861     static Parameters::DeviceType computeDeviceType(const InputDeviceContext& deviceContext);
862     static Parameters computeParameters(const InputDeviceContext& deviceContext);
863 };
864 
865 } // namespace android
866