• 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 // clang-format off
18 #include "../Macros.h"
19 // clang-format on
20 
21 #include <input/NamedEnum.h>
22 #include "TouchInputMapper.h"
23 
24 #include "CursorButtonAccumulator.h"
25 #include "CursorScrollAccumulator.h"
26 #include "TouchButtonAccumulator.h"
27 #include "TouchCursorInputMapperCommon.h"
28 
29 namespace android {
30 
31 // --- Constants ---
32 
33 // Maximum amount of latency to add to touch events while waiting for data from an
34 // external stylus.
35 static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
36 
37 // Maximum amount of time to wait on touch data before pushing out new pressure data.
38 static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
39 
40 // Artificial latency on synthetic events created from stylus data without corresponding touch
41 // data.
42 static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
43 
44 // --- Static Definitions ---
45 
46 template <typename T>
swap(T & a,T & b)47 inline static void swap(T& a, T& b) {
48     T temp = a;
49     a = b;
50     b = temp;
51 }
52 
calculateCommonVector(float a,float b)53 static float calculateCommonVector(float a, float b) {
54     if (a > 0 && b > 0) {
55         return a < b ? a : b;
56     } else if (a < 0 && b < 0) {
57         return a > b ? a : b;
58     } else {
59         return 0;
60     }
61 }
62 
distance(float x1,float y1,float x2,float y2)63 inline static float distance(float x1, float y1, float x2, float y2) {
64     return hypotf(x1 - x2, y1 - y2);
65 }
66 
signExtendNybble(int32_t value)67 inline static int32_t signExtendNybble(int32_t value) {
68     return value >= 8 ? value - 16 : value;
69 }
70 
71 // --- RawPointerAxes ---
72 
RawPointerAxes()73 RawPointerAxes::RawPointerAxes() {
74     clear();
75 }
76 
clear()77 void RawPointerAxes::clear() {
78     x.clear();
79     y.clear();
80     pressure.clear();
81     touchMajor.clear();
82     touchMinor.clear();
83     toolMajor.clear();
84     toolMinor.clear();
85     orientation.clear();
86     distance.clear();
87     tiltX.clear();
88     tiltY.clear();
89     trackingId.clear();
90     slot.clear();
91 }
92 
93 // --- RawPointerData ---
94 
RawPointerData()95 RawPointerData::RawPointerData() {
96     clear();
97 }
98 
clear()99 void RawPointerData::clear() {
100     pointerCount = 0;
101     clearIdBits();
102 }
103 
copyFrom(const RawPointerData & other)104 void RawPointerData::copyFrom(const RawPointerData& other) {
105     pointerCount = other.pointerCount;
106     hoveringIdBits = other.hoveringIdBits;
107     touchingIdBits = other.touchingIdBits;
108     canceledIdBits = other.canceledIdBits;
109 
110     for (uint32_t i = 0; i < pointerCount; i++) {
111         pointers[i] = other.pointers[i];
112 
113         int id = pointers[i].id;
114         idToIndex[id] = other.idToIndex[id];
115     }
116 }
117 
getCentroidOfTouchingPointers(float * outX,float * outY) const118 void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
119     float x = 0, y = 0;
120     uint32_t count = touchingIdBits.count();
121     if (count) {
122         for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
123             uint32_t id = idBits.clearFirstMarkedBit();
124             const Pointer& pointer = pointerForId(id);
125             x += pointer.x;
126             y += pointer.y;
127         }
128         x /= count;
129         y /= count;
130     }
131     *outX = x;
132     *outY = y;
133 }
134 
135 // --- CookedPointerData ---
136 
CookedPointerData()137 CookedPointerData::CookedPointerData() {
138     clear();
139 }
140 
clear()141 void CookedPointerData::clear() {
142     pointerCount = 0;
143     hoveringIdBits.clear();
144     touchingIdBits.clear();
145     canceledIdBits.clear();
146     validIdBits.clear();
147 }
148 
copyFrom(const CookedPointerData & other)149 void CookedPointerData::copyFrom(const CookedPointerData& other) {
150     pointerCount = other.pointerCount;
151     hoveringIdBits = other.hoveringIdBits;
152     touchingIdBits = other.touchingIdBits;
153     validIdBits = other.validIdBits;
154 
155     for (uint32_t i = 0; i < pointerCount; i++) {
156         pointerProperties[i].copyFrom(other.pointerProperties[i]);
157         pointerCoords[i].copyFrom(other.pointerCoords[i]);
158 
159         int id = pointerProperties[i].id;
160         idToIndex[id] = other.idToIndex[id];
161     }
162 }
163 
164 // --- TouchInputMapper ---
165 
TouchInputMapper(InputDeviceContext & deviceContext)166 TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
167       : InputMapper(deviceContext),
168         mSource(0),
169         mDeviceMode(DeviceMode::DISABLED),
170         mRawSurfaceWidth(-1),
171         mRawSurfaceHeight(-1),
172         mSurfaceLeft(0),
173         mSurfaceTop(0),
174         mSurfaceRight(0),
175         mSurfaceBottom(0),
176         mPhysicalWidth(-1),
177         mPhysicalHeight(-1),
178         mPhysicalLeft(0),
179         mPhysicalTop(0),
180         mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
181 
~TouchInputMapper()182 TouchInputMapper::~TouchInputMapper() {}
183 
getSources()184 uint32_t TouchInputMapper::getSources() {
185     return mSource;
186 }
187 
populateDeviceInfo(InputDeviceInfo * info)188 void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
189     InputMapper::populateDeviceInfo(info);
190 
191     if (mDeviceMode != DeviceMode::DISABLED) {
192         info->addMotionRange(mOrientedRanges.x);
193         info->addMotionRange(mOrientedRanges.y);
194         info->addMotionRange(mOrientedRanges.pressure);
195 
196         if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
197             // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
198             //
199             // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
200             // motion, i.e. the hardware dimensions, as the finger could move completely across the
201             // touchpad in one sample cycle.
202             const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
203             const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
204             info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
205                                  x.fuzz, x.resolution);
206             info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
207                                  y.fuzz, y.resolution);
208         }
209 
210         if (mOrientedRanges.haveSize) {
211             info->addMotionRange(mOrientedRanges.size);
212         }
213 
214         if (mOrientedRanges.haveTouchSize) {
215             info->addMotionRange(mOrientedRanges.touchMajor);
216             info->addMotionRange(mOrientedRanges.touchMinor);
217         }
218 
219         if (mOrientedRanges.haveToolSize) {
220             info->addMotionRange(mOrientedRanges.toolMajor);
221             info->addMotionRange(mOrientedRanges.toolMinor);
222         }
223 
224         if (mOrientedRanges.haveOrientation) {
225             info->addMotionRange(mOrientedRanges.orientation);
226         }
227 
228         if (mOrientedRanges.haveDistance) {
229             info->addMotionRange(mOrientedRanges.distance);
230         }
231 
232         if (mOrientedRanges.haveTilt) {
233             info->addMotionRange(mOrientedRanges.tilt);
234         }
235 
236         if (mCursorScrollAccumulator.haveRelativeVWheel()) {
237             info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
238                                  0.0f);
239         }
240         if (mCursorScrollAccumulator.haveRelativeHWheel()) {
241             info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
242                                  0.0f);
243         }
244         if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
245             const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
246             const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
247             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
248                                  x.fuzz, x.resolution);
249             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
250                                  y.fuzz, y.resolution);
251             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
252                                  x.fuzz, x.resolution);
253             info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
254                                  y.fuzz, y.resolution);
255         }
256         info->setButtonUnderPad(mParameters.hasButtonUnderPad);
257     }
258 }
259 
dump(std::string & dump)260 void TouchInputMapper::dump(std::string& dump) {
261     dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
262                          NamedEnum::string(mDeviceMode).c_str());
263     dumpParameters(dump);
264     dumpVirtualKeys(dump);
265     dumpRawPointerAxes(dump);
266     dumpCalibration(dump);
267     dumpAffineTransformation(dump);
268     dumpSurface(dump);
269 
270     dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
271     dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
272     dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
273     dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
274     dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
275     dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
276     dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
277     dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
278     dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
279     dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
280     dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
281     dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
282     dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
283     dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
284     dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
285     dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
286     dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
287 
288     dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
289     dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
290                          mLastRawState.rawPointerData.pointerCount);
291     for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
292         const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
293         dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
294                                      "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
295                                      "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
296                                      "toolType=%d, isHovering=%s\n",
297                              i, pointer.id, pointer.x, pointer.y, pointer.pressure,
298                              pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
299                              pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
300                              pointer.distance, pointer.toolType, toString(pointer.isHovering));
301     }
302 
303     dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
304                          mLastCookedState.buttonState);
305     dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
306                          mLastCookedState.cookedPointerData.pointerCount);
307     for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
308         const PointerProperties& pointerProperties =
309                 mLastCookedState.cookedPointerData.pointerProperties[i];
310         const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
311         dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
312                                      "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
313                                      "toolMajor=%0.3f, toolMinor=%0.3f, "
314                                      "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
315                                      "toolType=%d, isHovering=%s\n",
316                              i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
317                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
318                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
319                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
320                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
321                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
322                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
323                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
324                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
325                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
326                              pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
327                              pointerProperties.toolType,
328                              toString(mLastCookedState.cookedPointerData.isHovering(i)));
329     }
330 
331     dump += INDENT3 "Stylus Fusion:\n";
332     dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
333                          toString(mExternalStylusConnected));
334     dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
335     dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
336                          mExternalStylusFusionTimeout);
337     dump += INDENT3 "External Stylus State:\n";
338     dumpStylusState(dump, mExternalStylusState);
339 
340     if (mDeviceMode == DeviceMode::POINTER) {
341         dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
342         dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
343         dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
344         dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
345         dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
346         dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
347     }
348 }
349 
configure(nsecs_t when,const InputReaderConfiguration * config,uint32_t changes)350 void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351                                  uint32_t changes) {
352     InputMapper::configure(when, config, changes);
353 
354     mConfig = *config;
355 
356     if (!changes) { // first time only
357         // Configure basic parameters.
358         configureParameters();
359 
360         // Configure common accumulators.
361         mCursorScrollAccumulator.configure(getDeviceContext());
362         mTouchButtonAccumulator.configure(getDeviceContext());
363 
364         // Configure absolute axis information.
365         configureRawPointerAxes();
366 
367         // Prepare input device calibration.
368         parseCalibration();
369         resolveCalibration();
370     }
371 
372     if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373         // Update location calibration to reflect current settings
374         updateAffineTransformation();
375     }
376 
377     if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378         // Update pointer speed.
379         mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380         mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381         mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382     }
383 
384     bool resetNeeded = false;
385     if (!changes ||
386         (changes &
387          (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
388           InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
389           InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390           InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391           InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392         // Configure device sources, surface dimensions, orientation and
393         // scaling factors.
394         configureSurface(when, &resetNeeded);
395     }
396 
397     if (changes && resetNeeded) {
398         // Send reset, unless this is the first time the device has been configured,
399         // in which case the reader will call reset itself after all mappers are ready.
400         NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
401         getListener()->notifyDeviceReset(&args);
402     }
403 }
404 
resolveExternalStylusPresence()405 void TouchInputMapper::resolveExternalStylusPresence() {
406     std::vector<InputDeviceInfo> devices;
407     getContext()->getExternalStylusDevices(devices);
408     mExternalStylusConnected = !devices.empty();
409 
410     if (!mExternalStylusConnected) {
411         resetExternalStylus();
412     }
413 }
414 
configureParameters()415 void TouchInputMapper::configureParameters() {
416     // Use the pointer presentation mode for devices that do not support distinct
417     // multitouch.  The spot-based presentation relies on being able to accurately
418     // locate two or more fingers on the touch pad.
419     mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
420             ? Parameters::GestureMode::SINGLE_TOUCH
421             : Parameters::GestureMode::MULTI_TOUCH;
422 
423     String8 gestureModeString;
424     if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425                                                              gestureModeString)) {
426         if (gestureModeString == "single-touch") {
427             mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
428         } else if (gestureModeString == "multi-touch") {
429             mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
430         } else if (gestureModeString != "default") {
431             ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432         }
433     }
434 
435     if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
436         // The device is a touch screen.
437         mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
438     } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
439         // The device is a pointing device like a track pad.
440         mParameters.deviceType = Parameters::DeviceType::POINTER;
441     } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442                getDeviceContext().hasRelativeAxis(REL_Y)) {
443         // The device is a cursor device with a touch pad attached.
444         // By default don't use the touch pad to move the pointer.
445         mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
446     } else {
447         // The device is a touch pad of unknown purpose.
448         mParameters.deviceType = Parameters::DeviceType::POINTER;
449     }
450 
451     mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
452 
453     String8 deviceTypeString;
454     if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455                                                              deviceTypeString)) {
456         if (deviceTypeString == "touchScreen") {
457             mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
458         } else if (deviceTypeString == "touchPad") {
459             mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
460         } else if (deviceTypeString == "touchNavigation") {
461             mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
462         } else if (deviceTypeString == "pointer") {
463             mParameters.deviceType = Parameters::DeviceType::POINTER;
464         } else if (deviceTypeString != "default") {
465             ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466         }
467     }
468 
469     mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
470     getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471                                                          mParameters.orientationAware);
472 
473     mParameters.hasAssociatedDisplay = false;
474     mParameters.associatedDisplayIsExternal = false;
475     if (mParameters.orientationAware ||
476         mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477         mParameters.deviceType == Parameters::DeviceType::POINTER) {
478         mParameters.hasAssociatedDisplay = true;
479         if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
480             mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
481             String8 uniqueDisplayId;
482             getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483                                                                  uniqueDisplayId);
484             mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485         }
486     }
487     if (getDeviceContext().getAssociatedDisplayPort()) {
488         mParameters.hasAssociatedDisplay = true;
489     }
490 
491     // Initial downs on external touch devices should wake the device.
492     // Normally we don't do this for internal touch screens to prevent them from waking
493     // up in your pocket but you can enable it using the input device configuration.
494     mParameters.wake = getDeviceContext().isExternal();
495     getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
496 }
497 
dumpParameters(std::string & dump)498 void TouchInputMapper::dumpParameters(std::string& dump) {
499     dump += INDENT3 "Parameters:\n";
500 
501     dump += INDENT4 "GestureMode: " + NamedEnum::string(mParameters.gestureMode) + "\n";
502 
503     dump += INDENT4 "DeviceType: " + NamedEnum::string(mParameters.deviceType) + "\n";
504 
505     dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
506                                  "displayId='%s'\n",
507                          toString(mParameters.hasAssociatedDisplay),
508                          toString(mParameters.associatedDisplayIsExternal),
509                          mParameters.uniqueDisplayId.c_str());
510     dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
511 }
512 
configureRawPointerAxes()513 void TouchInputMapper::configureRawPointerAxes() {
514     mRawPointerAxes.clear();
515 }
516 
dumpRawPointerAxes(std::string & dump)517 void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
518     dump += INDENT3 "Raw Touch Axes:\n";
519     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
520     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
521     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
522     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
523     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
524     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
525     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
526     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
527     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
528     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
529     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
530     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
531     dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
532 }
533 
hasExternalStylus() const534 bool TouchInputMapper::hasExternalStylus() const {
535     return mExternalStylusConnected;
536 }
537 
538 /**
539  * Determine which DisplayViewport to use.
540  * 1. If display port is specified, return the matching viewport. If matching viewport not
541  * found, then return.
542  * 2. Always use the suggested viewport from WindowManagerService for pointers.
543  * 3. If a device has associated display, get the matching viewport by either unique id or by
544  * the display type (internal or external).
545  * 4. Otherwise, use a non-display viewport.
546  */
findViewport()547 std::optional<DisplayViewport> TouchInputMapper::findViewport() {
548     if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
549         const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
550         if (displayPort) {
551             // Find the viewport that contains the same port
552             return getDeviceContext().getAssociatedViewport();
553         }
554 
555         if (mDeviceMode == DeviceMode::POINTER) {
556             std::optional<DisplayViewport> viewport =
557                     mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
558             if (viewport) {
559                 return viewport;
560             } else {
561                 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
562                       mConfig.defaultPointerDisplayId);
563             }
564         }
565 
566         // Check if uniqueDisplayId is specified in idc file.
567         if (!mParameters.uniqueDisplayId.empty()) {
568             return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
569         }
570 
571         ViewportType viewportTypeToUse;
572         if (mParameters.associatedDisplayIsExternal) {
573             viewportTypeToUse = ViewportType::EXTERNAL;
574         } else {
575             viewportTypeToUse = ViewportType::INTERNAL;
576         }
577 
578         std::optional<DisplayViewport> viewport =
579                 mConfig.getDisplayViewportByType(viewportTypeToUse);
580         if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
581             ALOGW("Input device %s should be associated with external display, "
582                   "fallback to internal one for the external viewport is not found.",
583                   getDeviceName().c_str());
584             viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
585         }
586 
587         return viewport;
588     }
589 
590     // No associated display, return a non-display viewport.
591     DisplayViewport newViewport;
592     // Raw width and height in the natural orientation.
593     int32_t rawWidth = mRawPointerAxes.getRawWidth();
594     int32_t rawHeight = mRawPointerAxes.getRawHeight();
595     newViewport.setNonDisplayViewport(rawWidth, rawHeight);
596     return std::make_optional(newViewport);
597 }
598 
configureSurface(nsecs_t when,bool * outResetNeeded)599 void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
600     DeviceMode oldDeviceMode = mDeviceMode;
601 
602     resolveExternalStylusPresence();
603 
604     // Determine device mode.
605     if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
606         mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
607         mSource = AINPUT_SOURCE_MOUSE;
608         mDeviceMode = DeviceMode::POINTER;
609         if (hasStylus()) {
610             mSource |= AINPUT_SOURCE_STYLUS;
611         }
612     } else if (isTouchScreen()) {
613         mSource = AINPUT_SOURCE_TOUCHSCREEN;
614         mDeviceMode = DeviceMode::DIRECT;
615         if (hasStylus()) {
616             mSource |= AINPUT_SOURCE_STYLUS;
617         }
618         if (hasExternalStylus()) {
619             mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
620         }
621     } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
622         mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
623         mDeviceMode = DeviceMode::NAVIGATION;
624     } else {
625         mSource = AINPUT_SOURCE_TOUCHPAD;
626         mDeviceMode = DeviceMode::UNSCALED;
627     }
628 
629     // Ensure we have valid X and Y axes.
630     if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
631         ALOGW("Touch device '%s' did not report support for X or Y axis!  "
632               "The device will be inoperable.",
633               getDeviceName().c_str());
634         mDeviceMode = DeviceMode::DISABLED;
635         return;
636     }
637 
638     // Get associated display dimensions.
639     std::optional<DisplayViewport> newViewport = findViewport();
640     if (!newViewport) {
641         ALOGI("Touch device '%s' could not query the properties of its associated "
642               "display.  The device will be inoperable until the display size "
643               "becomes available.",
644               getDeviceName().c_str());
645         mDeviceMode = DeviceMode::DISABLED;
646         return;
647     }
648 
649     if (!newViewport->isActive) {
650         ALOGI("Disabling %s (device %i) because the associated viewport is not active",
651               getDeviceName().c_str(), getDeviceId());
652         mDeviceMode = DeviceMode::DISABLED;
653         return;
654     }
655 
656     // Raw width and height in the natural orientation.
657     int32_t rawWidth = mRawPointerAxes.getRawWidth();
658     int32_t rawHeight = mRawPointerAxes.getRawHeight();
659 
660     bool viewportChanged = mViewport != *newViewport;
661     bool skipViewportUpdate = false;
662     if (viewportChanged) {
663         bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
664         mViewport = *newViewport;
665 
666         if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
667             // Convert rotated viewport to natural surface coordinates.
668             int32_t naturalLogicalWidth, naturalLogicalHeight;
669             int32_t naturalPhysicalWidth, naturalPhysicalHeight;
670             int32_t naturalPhysicalLeft, naturalPhysicalTop;
671             int32_t naturalDeviceWidth, naturalDeviceHeight;
672             switch (mViewport.orientation) {
673                 case DISPLAY_ORIENTATION_90:
674                     naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
675                     naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
676                     naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
677                     naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
678                     naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
679                     naturalPhysicalTop = mViewport.physicalLeft;
680                     naturalDeviceWidth = mViewport.deviceHeight;
681                     naturalDeviceHeight = mViewport.deviceWidth;
682                     break;
683                 case DISPLAY_ORIENTATION_180:
684                     naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
685                     naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
686                     naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
687                     naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
688                     naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
689                     naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
690                     naturalDeviceWidth = mViewport.deviceWidth;
691                     naturalDeviceHeight = mViewport.deviceHeight;
692                     break;
693                 case DISPLAY_ORIENTATION_270:
694                     naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
695                     naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
696                     naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
697                     naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
698                     naturalPhysicalLeft = mViewport.physicalTop;
699                     naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
700                     naturalDeviceWidth = mViewport.deviceHeight;
701                     naturalDeviceHeight = mViewport.deviceWidth;
702                     break;
703                 case DISPLAY_ORIENTATION_0:
704                 default:
705                     naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
706                     naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
707                     naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
708                     naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
709                     naturalPhysicalLeft = mViewport.physicalLeft;
710                     naturalPhysicalTop = mViewport.physicalTop;
711                     naturalDeviceWidth = mViewport.deviceWidth;
712                     naturalDeviceHeight = mViewport.deviceHeight;
713                     break;
714             }
715 
716             if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
717                 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
718                 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
719                 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
720             }
721 
722             mPhysicalWidth = naturalPhysicalWidth;
723             mPhysicalHeight = naturalPhysicalHeight;
724             mPhysicalLeft = naturalPhysicalLeft;
725             mPhysicalTop = naturalPhysicalTop;
726 
727             const int32_t oldSurfaceWidth = mRawSurfaceWidth;
728             const int32_t oldSurfaceHeight = mRawSurfaceHeight;
729             mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
730             mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
731             mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
732             mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
733             mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
734             mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
735 
736             if (isPerWindowInputRotationEnabled()) {
737                 // When per-window input rotation is enabled, InputReader works in the un-rotated
738                 // coordinate space, so we don't need to do anything if the device is already
739                 // orientation-aware. If the device is not orientation-aware, then we need to apply
740                 // the inverse rotation of the display so that when the display rotation is applied
741                 // later as a part of the per-window transform, we get the expected screen
742                 // coordinates.
743                 mSurfaceOrientation = mParameters.orientationAware
744                         ? DISPLAY_ORIENTATION_0
745                         : getInverseRotation(mViewport.orientation);
746                 // For orientation-aware devices that work in the un-rotated coordinate space, the
747                 // viewport update should be skipped if it is only a change in the orientation.
748                 skipViewportUpdate = mParameters.orientationAware &&
749                         mRawSurfaceWidth == oldSurfaceWidth &&
750                         mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
751             } else {
752                 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
753                                                                    : DISPLAY_ORIENTATION_0;
754             }
755         } else {
756             mPhysicalWidth = rawWidth;
757             mPhysicalHeight = rawHeight;
758             mPhysicalLeft = 0;
759             mPhysicalTop = 0;
760 
761             mRawSurfaceWidth = rawWidth;
762             mRawSurfaceHeight = rawHeight;
763             mSurfaceLeft = 0;
764             mSurfaceTop = 0;
765             mSurfaceOrientation = DISPLAY_ORIENTATION_0;
766         }
767     }
768 
769     // If moving between pointer modes, need to reset some state.
770     bool deviceModeChanged = mDeviceMode != oldDeviceMode;
771     if (deviceModeChanged) {
772         mOrientedRanges.clear();
773     }
774 
775     // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
776     // preserve the cursor position.
777     if (mDeviceMode == DeviceMode::POINTER ||
778         (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
779         (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
780         if (mPointerController == nullptr) {
781             mPointerController = getContext()->getPointerController(getDeviceId());
782         }
783         if (mConfig.pointerCapture) {
784             mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
785         }
786     } else {
787         mPointerController.reset();
788     }
789 
790     if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
791         ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
792               "display id %d",
793               getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
794               mSurfaceOrientation, mDeviceMode, mViewport.displayId);
795 
796         // Configure X and Y factors.
797         mXScale = float(mRawSurfaceWidth) / rawWidth;
798         mYScale = float(mRawSurfaceHeight) / rawHeight;
799         mXTranslate = -mSurfaceLeft;
800         mYTranslate = -mSurfaceTop;
801         mXPrecision = 1.0f / mXScale;
802         mYPrecision = 1.0f / mYScale;
803 
804         mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
805         mOrientedRanges.x.source = mSource;
806         mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
807         mOrientedRanges.y.source = mSource;
808 
809         configureVirtualKeys();
810 
811         // Scale factor for terms that are not oriented in a particular axis.
812         // If the pixels are square then xScale == yScale otherwise we fake it
813         // by choosing an average.
814         mGeometricScale = avg(mXScale, mYScale);
815 
816         // Size of diagonal axis.
817         float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
818 
819         // Size factors.
820         if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
821             if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
822                 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
823             } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
824                 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
825             } else {
826                 mSizeScale = 0.0f;
827             }
828 
829             mOrientedRanges.haveTouchSize = true;
830             mOrientedRanges.haveToolSize = true;
831             mOrientedRanges.haveSize = true;
832 
833             mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
834             mOrientedRanges.touchMajor.source = mSource;
835             mOrientedRanges.touchMajor.min = 0;
836             mOrientedRanges.touchMajor.max = diagonalSize;
837             mOrientedRanges.touchMajor.flat = 0;
838             mOrientedRanges.touchMajor.fuzz = 0;
839             mOrientedRanges.touchMajor.resolution = 0;
840 
841             mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
842             mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
843 
844             mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
845             mOrientedRanges.toolMajor.source = mSource;
846             mOrientedRanges.toolMajor.min = 0;
847             mOrientedRanges.toolMajor.max = diagonalSize;
848             mOrientedRanges.toolMajor.flat = 0;
849             mOrientedRanges.toolMajor.fuzz = 0;
850             mOrientedRanges.toolMajor.resolution = 0;
851 
852             mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
853             mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
854 
855             mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
856             mOrientedRanges.size.source = mSource;
857             mOrientedRanges.size.min = 0;
858             mOrientedRanges.size.max = 1.0;
859             mOrientedRanges.size.flat = 0;
860             mOrientedRanges.size.fuzz = 0;
861             mOrientedRanges.size.resolution = 0;
862         } else {
863             mSizeScale = 0.0f;
864         }
865 
866         // Pressure factors.
867         mPressureScale = 0;
868         float pressureMax = 1.0;
869         if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
870             mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
871             if (mCalibration.havePressureScale) {
872                 mPressureScale = mCalibration.pressureScale;
873                 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
874             } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
875                 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
876             }
877         }
878 
879         mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
880         mOrientedRanges.pressure.source = mSource;
881         mOrientedRanges.pressure.min = 0;
882         mOrientedRanges.pressure.max = pressureMax;
883         mOrientedRanges.pressure.flat = 0;
884         mOrientedRanges.pressure.fuzz = 0;
885         mOrientedRanges.pressure.resolution = 0;
886 
887         // Tilt
888         mTiltXCenter = 0;
889         mTiltXScale = 0;
890         mTiltYCenter = 0;
891         mTiltYScale = 0;
892         mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
893         if (mHaveTilt) {
894             mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
895             mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
896             mTiltXScale = M_PI / 180;
897             mTiltYScale = M_PI / 180;
898 
899             mOrientedRanges.haveTilt = true;
900 
901             mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
902             mOrientedRanges.tilt.source = mSource;
903             mOrientedRanges.tilt.min = 0;
904             mOrientedRanges.tilt.max = M_PI_2;
905             mOrientedRanges.tilt.flat = 0;
906             mOrientedRanges.tilt.fuzz = 0;
907             mOrientedRanges.tilt.resolution = 0;
908         }
909 
910         // Orientation
911         mOrientationScale = 0;
912         if (mHaveTilt) {
913             mOrientedRanges.haveOrientation = true;
914 
915             mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
916             mOrientedRanges.orientation.source = mSource;
917             mOrientedRanges.orientation.min = -M_PI;
918             mOrientedRanges.orientation.max = M_PI;
919             mOrientedRanges.orientation.flat = 0;
920             mOrientedRanges.orientation.fuzz = 0;
921             mOrientedRanges.orientation.resolution = 0;
922         } else if (mCalibration.orientationCalibration !=
923                    Calibration::OrientationCalibration::NONE) {
924             if (mCalibration.orientationCalibration ==
925                 Calibration::OrientationCalibration::INTERPOLATED) {
926                 if (mRawPointerAxes.orientation.valid) {
927                     if (mRawPointerAxes.orientation.maxValue > 0) {
928                         mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
929                     } else if (mRawPointerAxes.orientation.minValue < 0) {
930                         mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
931                     } else {
932                         mOrientationScale = 0;
933                     }
934                 }
935             }
936 
937             mOrientedRanges.haveOrientation = true;
938 
939             mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
940             mOrientedRanges.orientation.source = mSource;
941             mOrientedRanges.orientation.min = -M_PI_2;
942             mOrientedRanges.orientation.max = M_PI_2;
943             mOrientedRanges.orientation.flat = 0;
944             mOrientedRanges.orientation.fuzz = 0;
945             mOrientedRanges.orientation.resolution = 0;
946         }
947 
948         // Distance
949         mDistanceScale = 0;
950         if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
951             if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
952                 if (mCalibration.haveDistanceScale) {
953                     mDistanceScale = mCalibration.distanceScale;
954                 } else {
955                     mDistanceScale = 1.0f;
956                 }
957             }
958 
959             mOrientedRanges.haveDistance = true;
960 
961             mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
962             mOrientedRanges.distance.source = mSource;
963             mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
964             mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
965             mOrientedRanges.distance.flat = 0;
966             mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
967             mOrientedRanges.distance.resolution = 0;
968         }
969 
970         // Compute oriented precision, scales and ranges.
971         // Note that the maximum value reported is an inclusive maximum value so it is one
972         // unit less than the total width or height of surface.
973         switch (mSurfaceOrientation) {
974             case DISPLAY_ORIENTATION_90:
975             case DISPLAY_ORIENTATION_270:
976                 mOrientedXPrecision = mYPrecision;
977                 mOrientedYPrecision = mXPrecision;
978 
979                 mOrientedRanges.x.min = mYTranslate;
980                 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
981                 mOrientedRanges.x.flat = 0;
982                 mOrientedRanges.x.fuzz = 0;
983                 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
984 
985                 mOrientedRanges.y.min = mXTranslate;
986                 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
987                 mOrientedRanges.y.flat = 0;
988                 mOrientedRanges.y.fuzz = 0;
989                 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
990                 break;
991 
992             default:
993                 mOrientedXPrecision = mXPrecision;
994                 mOrientedYPrecision = mYPrecision;
995 
996                 mOrientedRanges.x.min = mXTranslate;
997                 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
998                 mOrientedRanges.x.flat = 0;
999                 mOrientedRanges.x.fuzz = 0;
1000                 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1001 
1002                 mOrientedRanges.y.min = mYTranslate;
1003                 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
1004                 mOrientedRanges.y.flat = 0;
1005                 mOrientedRanges.y.fuzz = 0;
1006                 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1007                 break;
1008         }
1009 
1010         // Location
1011         updateAffineTransformation();
1012 
1013         if (mDeviceMode == DeviceMode::POINTER) {
1014             // Compute pointer gesture detection parameters.
1015             float rawDiagonal = hypotf(rawWidth, rawHeight);
1016             float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
1017 
1018             // Scale movements such that one whole swipe of the touch pad covers a
1019             // given area relative to the diagonal size of the display when no acceleration
1020             // is applied.
1021             // Assume that the touch pad has a square aspect ratio such that movements in
1022             // X and Y of the same number of raw units cover the same physical distance.
1023             mPointerXMovementScale =
1024                     mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1025             mPointerYMovementScale = mPointerXMovementScale;
1026 
1027             // Scale zooms to cover a smaller range of the display than movements do.
1028             // This value determines the area around the pointer that is affected by freeform
1029             // pointer gestures.
1030             mPointerXZoomScale =
1031                     mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1032             mPointerYZoomScale = mPointerXZoomScale;
1033 
1034             // Max width between pointers to detect a swipe gesture is more than some fraction
1035             // of the diagonal axis of the touch pad.  Touches that are wider than this are
1036             // translated into freeform gestures.
1037             mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1038 
1039             // Abort current pointer usages because the state has changed.
1040             const nsecs_t readTime = when; // synthetic event
1041             abortPointerUsage(when, readTime, 0 /*policyFlags*/);
1042         }
1043 
1044         // Inform the dispatcher about the changes.
1045         *outResetNeeded = true;
1046         bumpGeneration();
1047     }
1048 }
1049 
dumpSurface(std::string & dump)1050 void TouchInputMapper::dumpSurface(std::string& dump) {
1051     dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
1052     dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1053     dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
1054     dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1055     dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
1056     dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1057     dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
1058     dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1059     dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1060     dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1061     dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1062     dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1063 }
1064 
configureVirtualKeys()1065 void TouchInputMapper::configureVirtualKeys() {
1066     std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
1067     getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
1068 
1069     mVirtualKeys.clear();
1070 
1071     if (virtualKeyDefinitions.size() == 0) {
1072         return;
1073     }
1074 
1075     int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1076     int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1077     int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1078     int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1079 
1080     for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1081         VirtualKey virtualKey;
1082 
1083         virtualKey.scanCode = virtualKeyDefinition.scanCode;
1084         int32_t keyCode;
1085         int32_t dummyKeyMetaState;
1086         uint32_t flags;
1087         if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1088                                       &flags)) {
1089             ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1090             continue; // drop the key
1091         }
1092 
1093         virtualKey.keyCode = keyCode;
1094         virtualKey.flags = flags;
1095 
1096         // convert the key definition's display coordinates into touch coordinates for a hit box
1097         int32_t halfWidth = virtualKeyDefinition.width / 2;
1098         int32_t halfHeight = virtualKeyDefinition.height / 2;
1099 
1100         virtualKey.hitLeft =
1101                 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
1102                 touchScreenLeft;
1103         virtualKey.hitRight =
1104                 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
1105                 touchScreenLeft;
1106         virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1107                         mRawSurfaceHeight +
1108                 touchScreenTop;
1109         virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1110                         mRawSurfaceHeight +
1111                 touchScreenTop;
1112         mVirtualKeys.push_back(virtualKey);
1113     }
1114 }
1115 
dumpVirtualKeys(std::string & dump)1116 void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1117     if (!mVirtualKeys.empty()) {
1118         dump += INDENT3 "Virtual Keys:\n";
1119 
1120         for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1121             const VirtualKey& virtualKey = mVirtualKeys[i];
1122             dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1123                                          "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1124                                  i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1125                                  virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1126         }
1127     }
1128 }
1129 
parseCalibration()1130 void TouchInputMapper::parseCalibration() {
1131     const PropertyMap& in = getDeviceContext().getConfiguration();
1132     Calibration& out = mCalibration;
1133 
1134     // Size
1135     out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
1136     String8 sizeCalibrationString;
1137     if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1138         if (sizeCalibrationString == "none") {
1139             out.sizeCalibration = Calibration::SizeCalibration::NONE;
1140         } else if (sizeCalibrationString == "geometric") {
1141             out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
1142         } else if (sizeCalibrationString == "diameter") {
1143             out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
1144         } else if (sizeCalibrationString == "box") {
1145             out.sizeCalibration = Calibration::SizeCalibration::BOX;
1146         } else if (sizeCalibrationString == "area") {
1147             out.sizeCalibration = Calibration::SizeCalibration::AREA;
1148         } else if (sizeCalibrationString != "default") {
1149             ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1150         }
1151     }
1152 
1153     out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1154     out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1155     out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1156 
1157     // Pressure
1158     out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
1159     String8 pressureCalibrationString;
1160     if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1161         if (pressureCalibrationString == "none") {
1162             out.pressureCalibration = Calibration::PressureCalibration::NONE;
1163         } else if (pressureCalibrationString == "physical") {
1164             out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
1165         } else if (pressureCalibrationString == "amplitude") {
1166             out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
1167         } else if (pressureCalibrationString != "default") {
1168             ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1169                   pressureCalibrationString.string());
1170         }
1171     }
1172 
1173     out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1174 
1175     // Orientation
1176     out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
1177     String8 orientationCalibrationString;
1178     if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1179         if (orientationCalibrationString == "none") {
1180             out.orientationCalibration = Calibration::OrientationCalibration::NONE;
1181         } else if (orientationCalibrationString == "interpolated") {
1182             out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
1183         } else if (orientationCalibrationString == "vector") {
1184             out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
1185         } else if (orientationCalibrationString != "default") {
1186             ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1187                   orientationCalibrationString.string());
1188         }
1189     }
1190 
1191     // Distance
1192     out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
1193     String8 distanceCalibrationString;
1194     if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1195         if (distanceCalibrationString == "none") {
1196             out.distanceCalibration = Calibration::DistanceCalibration::NONE;
1197         } else if (distanceCalibrationString == "scaled") {
1198             out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
1199         } else if (distanceCalibrationString != "default") {
1200             ALOGW("Invalid value for touch.distance.calibration: '%s'",
1201                   distanceCalibrationString.string());
1202         }
1203     }
1204 
1205     out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1206 
1207     out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
1208     String8 coverageCalibrationString;
1209     if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1210         if (coverageCalibrationString == "none") {
1211             out.coverageCalibration = Calibration::CoverageCalibration::NONE;
1212         } else if (coverageCalibrationString == "box") {
1213             out.coverageCalibration = Calibration::CoverageCalibration::BOX;
1214         } else if (coverageCalibrationString != "default") {
1215             ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1216                   coverageCalibrationString.string());
1217         }
1218     }
1219 }
1220 
resolveCalibration()1221 void TouchInputMapper::resolveCalibration() {
1222     // Size
1223     if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
1224         if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1225             mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
1226         }
1227     } else {
1228         mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
1229     }
1230 
1231     // Pressure
1232     if (mRawPointerAxes.pressure.valid) {
1233         if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1234             mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
1235         }
1236     } else {
1237         mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
1238     }
1239 
1240     // Orientation
1241     if (mRawPointerAxes.orientation.valid) {
1242         if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1243             mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
1244         }
1245     } else {
1246         mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
1247     }
1248 
1249     // Distance
1250     if (mRawPointerAxes.distance.valid) {
1251         if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1252             mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
1253         }
1254     } else {
1255         mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
1256     }
1257 
1258     // Coverage
1259     if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1260         mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
1261     }
1262 }
1263 
dumpCalibration(std::string & dump)1264 void TouchInputMapper::dumpCalibration(std::string& dump) {
1265     dump += INDENT3 "Calibration:\n";
1266 
1267     // Size
1268     switch (mCalibration.sizeCalibration) {
1269         case Calibration::SizeCalibration::NONE:
1270             dump += INDENT4 "touch.size.calibration: none\n";
1271             break;
1272         case Calibration::SizeCalibration::GEOMETRIC:
1273             dump += INDENT4 "touch.size.calibration: geometric\n";
1274             break;
1275         case Calibration::SizeCalibration::DIAMETER:
1276             dump += INDENT4 "touch.size.calibration: diameter\n";
1277             break;
1278         case Calibration::SizeCalibration::BOX:
1279             dump += INDENT4 "touch.size.calibration: box\n";
1280             break;
1281         case Calibration::SizeCalibration::AREA:
1282             dump += INDENT4 "touch.size.calibration: area\n";
1283             break;
1284         default:
1285             ALOG_ASSERT(false);
1286     }
1287 
1288     if (mCalibration.haveSizeScale) {
1289         dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1290     }
1291 
1292     if (mCalibration.haveSizeBias) {
1293         dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1294     }
1295 
1296     if (mCalibration.haveSizeIsSummed) {
1297         dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1298                              toString(mCalibration.sizeIsSummed));
1299     }
1300 
1301     // Pressure
1302     switch (mCalibration.pressureCalibration) {
1303         case Calibration::PressureCalibration::NONE:
1304             dump += INDENT4 "touch.pressure.calibration: none\n";
1305             break;
1306         case Calibration::PressureCalibration::PHYSICAL:
1307             dump += INDENT4 "touch.pressure.calibration: physical\n";
1308             break;
1309         case Calibration::PressureCalibration::AMPLITUDE:
1310             dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1311             break;
1312         default:
1313             ALOG_ASSERT(false);
1314     }
1315 
1316     if (mCalibration.havePressureScale) {
1317         dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1318     }
1319 
1320     // Orientation
1321     switch (mCalibration.orientationCalibration) {
1322         case Calibration::OrientationCalibration::NONE:
1323             dump += INDENT4 "touch.orientation.calibration: none\n";
1324             break;
1325         case Calibration::OrientationCalibration::INTERPOLATED:
1326             dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1327             break;
1328         case Calibration::OrientationCalibration::VECTOR:
1329             dump += INDENT4 "touch.orientation.calibration: vector\n";
1330             break;
1331         default:
1332             ALOG_ASSERT(false);
1333     }
1334 
1335     // Distance
1336     switch (mCalibration.distanceCalibration) {
1337         case Calibration::DistanceCalibration::NONE:
1338             dump += INDENT4 "touch.distance.calibration: none\n";
1339             break;
1340         case Calibration::DistanceCalibration::SCALED:
1341             dump += INDENT4 "touch.distance.calibration: scaled\n";
1342             break;
1343         default:
1344             ALOG_ASSERT(false);
1345     }
1346 
1347     if (mCalibration.haveDistanceScale) {
1348         dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1349     }
1350 
1351     switch (mCalibration.coverageCalibration) {
1352         case Calibration::CoverageCalibration::NONE:
1353             dump += INDENT4 "touch.coverage.calibration: none\n";
1354             break;
1355         case Calibration::CoverageCalibration::BOX:
1356             dump += INDENT4 "touch.coverage.calibration: box\n";
1357             break;
1358         default:
1359             ALOG_ASSERT(false);
1360     }
1361 }
1362 
dumpAffineTransformation(std::string & dump)1363 void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1364     dump += INDENT3 "Affine Transformation:\n";
1365 
1366     dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1367     dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1368     dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1369     dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1370     dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1371     dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1372 }
1373 
updateAffineTransformation()1374 void TouchInputMapper::updateAffineTransformation() {
1375     mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
1376                                                                  mSurfaceOrientation);
1377 }
1378 
reset(nsecs_t when)1379 void TouchInputMapper::reset(nsecs_t when) {
1380     mCursorButtonAccumulator.reset(getDeviceContext());
1381     mCursorScrollAccumulator.reset(getDeviceContext());
1382     mTouchButtonAccumulator.reset(getDeviceContext());
1383 
1384     mPointerVelocityControl.reset();
1385     mWheelXVelocityControl.reset();
1386     mWheelYVelocityControl.reset();
1387 
1388     mRawStatesPending.clear();
1389     mCurrentRawState.clear();
1390     mCurrentCookedState.clear();
1391     mLastRawState.clear();
1392     mLastCookedState.clear();
1393     mPointerUsage = PointerUsage::NONE;
1394     mSentHoverEnter = false;
1395     mHavePointerIds = false;
1396     mCurrentMotionAborted = false;
1397     mDownTime = 0;
1398 
1399     mCurrentVirtualKey.down = false;
1400 
1401     mPointerGesture.reset();
1402     mPointerSimple.reset();
1403     resetExternalStylus();
1404 
1405     if (mPointerController != nullptr) {
1406         mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1407         mPointerController->clearSpots();
1408     }
1409 
1410     InputMapper::reset(when);
1411 }
1412 
resetExternalStylus()1413 void TouchInputMapper::resetExternalStylus() {
1414     mExternalStylusState.clear();
1415     mExternalStylusId = -1;
1416     mExternalStylusFusionTimeout = LLONG_MAX;
1417     mExternalStylusDataPending = false;
1418 }
1419 
clearStylusDataPendingFlags()1420 void TouchInputMapper::clearStylusDataPendingFlags() {
1421     mExternalStylusDataPending = false;
1422     mExternalStylusFusionTimeout = LLONG_MAX;
1423 }
1424 
process(const RawEvent * rawEvent)1425 void TouchInputMapper::process(const RawEvent* rawEvent) {
1426     mCursorButtonAccumulator.process(rawEvent);
1427     mCursorScrollAccumulator.process(rawEvent);
1428     mTouchButtonAccumulator.process(rawEvent);
1429 
1430     if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1431         sync(rawEvent->when, rawEvent->readTime);
1432     }
1433 }
1434 
sync(nsecs_t when,nsecs_t readTime)1435 void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1436     // Push a new state.
1437     mRawStatesPending.emplace_back();
1438 
1439     RawState& next = mRawStatesPending.back();
1440     next.clear();
1441     next.when = when;
1442     next.readTime = readTime;
1443 
1444     // Sync button state.
1445     next.buttonState =
1446             mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1447 
1448     // Sync scroll
1449     next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1450     next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1451     mCursorScrollAccumulator.finishSync();
1452 
1453     // Sync touch
1454     syncTouch(when, &next);
1455 
1456     // The last RawState is the actually second to last, since we just added a new state
1457     const RawState& last =
1458             mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
1459 
1460     // Assign pointer ids.
1461     if (!mHavePointerIds) {
1462         assignPointerIds(last, next);
1463     }
1464 
1465 #if DEBUG_RAW_EVENTS
1466     ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1467           "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1468           last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1469           last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1470           last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1471           next.rawPointerData.canceledIdBits.value);
1472 #endif
1473 
1474     if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1475         !next.rawPointerData.hoveringIdBits.isEmpty() &&
1476         last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1477         ALOGI("Multi-touch contains some hovering ids 0x%08x",
1478               next.rawPointerData.hoveringIdBits.value);
1479     }
1480 
1481     processRawTouches(false /*timeout*/);
1482 }
1483 
processRawTouches(bool timeout)1484 void TouchInputMapper::processRawTouches(bool timeout) {
1485     if (mDeviceMode == DeviceMode::DISABLED) {
1486         // Drop all input if the device is disabled.
1487         cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
1488         mCurrentCookedState.clear();
1489         updateTouchSpots();
1490         return;
1491     }
1492 
1493     // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1494     // valid and must go through the full cook and dispatch cycle. This ensures that anything
1495     // touching the current state will only observe the events that have been dispatched to the
1496     // rest of the pipeline.
1497     const size_t N = mRawStatesPending.size();
1498     size_t count;
1499     for (count = 0; count < N; count++) {
1500         const RawState& next = mRawStatesPending[count];
1501 
1502         // A failure to assign the stylus id means that we're waiting on stylus data
1503         // and so should defer the rest of the pipeline.
1504         if (assignExternalStylusId(next, timeout)) {
1505             break;
1506         }
1507 
1508         // All ready to go.
1509         clearStylusDataPendingFlags();
1510         mCurrentRawState.copyFrom(next);
1511         if (mCurrentRawState.when < mLastRawState.when) {
1512             mCurrentRawState.when = mLastRawState.when;
1513             mCurrentRawState.readTime = mLastRawState.readTime;
1514         }
1515         cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
1516     }
1517     if (count != 0) {
1518         mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1519     }
1520 
1521     if (mExternalStylusDataPending) {
1522         if (timeout) {
1523             nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1524             clearStylusDataPendingFlags();
1525             mCurrentRawState.copyFrom(mLastRawState);
1526 #if DEBUG_STYLUS_FUSION
1527             ALOGD("Timeout expired, synthesizing event with new stylus data");
1528 #endif
1529             const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1530             cookAndDispatch(when, readTime);
1531         } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1532             mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1533             getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1534         }
1535     }
1536 }
1537 
cookAndDispatch(nsecs_t when,nsecs_t readTime)1538 void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1539     // Always start with a clean state.
1540     mCurrentCookedState.clear();
1541 
1542     // Apply stylus buttons to current raw state.
1543     applyExternalStylusButtonState(when);
1544 
1545     // Handle policy on initial down or hover events.
1546     bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1547             mCurrentRawState.rawPointerData.pointerCount != 0;
1548 
1549     uint32_t policyFlags = 0;
1550     bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1551     if (initialDown || buttonsPressed) {
1552         // If this is a touch screen, hide the pointer on an initial down.
1553         if (mDeviceMode == DeviceMode::DIRECT) {
1554             getContext()->fadePointer();
1555         }
1556 
1557         if (mParameters.wake) {
1558             policyFlags |= POLICY_FLAG_WAKE;
1559         }
1560     }
1561 
1562     // Consume raw off-screen touches before cooking pointer data.
1563     // If touches are consumed, subsequent code will not receive any pointer data.
1564     if (consumeRawTouches(when, readTime, policyFlags)) {
1565         mCurrentRawState.rawPointerData.clear();
1566     }
1567 
1568     // Cook pointer data.  This call populates the mCurrentCookedState.cookedPointerData structure
1569     // with cooked pointer data that has the same ids and indices as the raw data.
1570     // The following code can use either the raw or cooked data, as needed.
1571     cookPointerData();
1572 
1573     // Apply stylus pressure to current cooked state.
1574     applyExternalStylusTouchState(when);
1575 
1576     // Synthesize key down from raw buttons if needed.
1577     synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1578                          mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1579                          mCurrentCookedState.buttonState);
1580 
1581     // Dispatch the touches either directly or by translation through a pointer on screen.
1582     if (mDeviceMode == DeviceMode::POINTER) {
1583         for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1584             uint32_t id = idBits.clearFirstMarkedBit();
1585             const RawPointerData::Pointer& pointer =
1586                     mCurrentRawState.rawPointerData.pointerForId(id);
1587             if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1588                 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1589                 mCurrentCookedState.stylusIdBits.markBit(id);
1590             } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1591                        pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1592                 mCurrentCookedState.fingerIdBits.markBit(id);
1593             } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1594                 mCurrentCookedState.mouseIdBits.markBit(id);
1595             }
1596         }
1597         for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1598             uint32_t id = idBits.clearFirstMarkedBit();
1599             const RawPointerData::Pointer& pointer =
1600                     mCurrentRawState.rawPointerData.pointerForId(id);
1601             if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1602                 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1603                 mCurrentCookedState.stylusIdBits.markBit(id);
1604             }
1605         }
1606 
1607         // Stylus takes precedence over all tools, then mouse, then finger.
1608         PointerUsage pointerUsage = mPointerUsage;
1609         if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1610             mCurrentCookedState.mouseIdBits.clear();
1611             mCurrentCookedState.fingerIdBits.clear();
1612             pointerUsage = PointerUsage::STYLUS;
1613         } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1614             mCurrentCookedState.fingerIdBits.clear();
1615             pointerUsage = PointerUsage::MOUSE;
1616         } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1617                    isPointerDown(mCurrentRawState.buttonState)) {
1618             pointerUsage = PointerUsage::GESTURES;
1619         }
1620 
1621         dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
1622     } else {
1623         updateTouchSpots();
1624 
1625         if (!mCurrentMotionAborted) {
1626             dispatchButtonRelease(when, readTime, policyFlags);
1627             dispatchHoverExit(when, readTime, policyFlags);
1628             dispatchTouches(when, readTime, policyFlags);
1629             dispatchHoverEnterAndMove(when, readTime, policyFlags);
1630             dispatchButtonPress(when, readTime, policyFlags);
1631         }
1632 
1633         if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1634             mCurrentMotionAborted = false;
1635         }
1636     }
1637 
1638     // Synthesize key up from raw buttons if needed.
1639     synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
1640                          mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1641                          mCurrentCookedState.buttonState);
1642 
1643     // Clear some transient state.
1644     mCurrentRawState.rawVScroll = 0;
1645     mCurrentRawState.rawHScroll = 0;
1646 
1647     // Copy current touch to last touch in preparation for the next cycle.
1648     mLastRawState.copyFrom(mCurrentRawState);
1649     mLastCookedState.copyFrom(mCurrentCookedState);
1650 }
1651 
updateTouchSpots()1652 void TouchInputMapper::updateTouchSpots() {
1653     if (!mConfig.showTouches || mPointerController == nullptr) {
1654         return;
1655     }
1656 
1657     // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1658     // clear touch spots.
1659     if (mDeviceMode != DeviceMode::DIRECT &&
1660         (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1661         return;
1662     }
1663 
1664     mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1665     mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1666 
1667     mPointerController->setButtonState(mCurrentRawState.buttonState);
1668     setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1669                   mCurrentCookedState.cookedPointerData.idToIndex,
1670                   mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
1671 }
1672 
isTouchScreen()1673 bool TouchInputMapper::isTouchScreen() {
1674     return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1675             mParameters.hasAssociatedDisplay;
1676 }
1677 
applyExternalStylusButtonState(nsecs_t when)1678 void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
1679     if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
1680         mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1681     }
1682 }
1683 
applyExternalStylusTouchState(nsecs_t when)1684 void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1685     CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1686     const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1687 
1688     if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1689         float pressure = mExternalStylusState.pressure;
1690         if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1691             const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1692             pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1693         }
1694         PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1695         coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1696 
1697         PointerProperties& properties =
1698                 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1699         if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1700             properties.toolType = mExternalStylusState.toolType;
1701         }
1702     }
1703 }
1704 
assignExternalStylusId(const RawState & state,bool timeout)1705 bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
1706     if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
1707         return false;
1708     }
1709 
1710     const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1711             state.rawPointerData.pointerCount != 0;
1712     if (initialDown) {
1713         if (mExternalStylusState.pressure != 0.0f) {
1714 #if DEBUG_STYLUS_FUSION
1715             ALOGD("Have both stylus and touch data, beginning fusion");
1716 #endif
1717             mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1718         } else if (timeout) {
1719 #if DEBUG_STYLUS_FUSION
1720             ALOGD("Timeout expired, assuming touch is not a stylus.");
1721 #endif
1722             resetExternalStylus();
1723         } else {
1724             if (mExternalStylusFusionTimeout == LLONG_MAX) {
1725                 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1726             }
1727 #if DEBUG_STYLUS_FUSION
1728             ALOGD("No stylus data but stylus is connected, requesting timeout "
1729                   "(%" PRId64 "ms)",
1730                   mExternalStylusFusionTimeout);
1731 #endif
1732             getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1733             return true;
1734         }
1735     }
1736 
1737     // Check if the stylus pointer has gone up.
1738     if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1739 #if DEBUG_STYLUS_FUSION
1740         ALOGD("Stylus pointer is going up");
1741 #endif
1742         mExternalStylusId = -1;
1743     }
1744 
1745     return false;
1746 }
1747 
timeoutExpired(nsecs_t when)1748 void TouchInputMapper::timeoutExpired(nsecs_t when) {
1749     if (mDeviceMode == DeviceMode::POINTER) {
1750         if (mPointerUsage == PointerUsage::GESTURES) {
1751             // Since this is a synthetic event, we can consider its latency to be zero
1752             const nsecs_t readTime = when;
1753             dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
1754         }
1755     } else if (mDeviceMode == DeviceMode::DIRECT) {
1756         if (mExternalStylusFusionTimeout < when) {
1757             processRawTouches(true /*timeout*/);
1758         } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1759             getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1760         }
1761     }
1762 }
1763 
updateExternalStylusState(const StylusState & state)1764 void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1765     mExternalStylusState.copyFrom(state);
1766     if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1767         // We're either in the middle of a fused stream of data or we're waiting on data before
1768         // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1769         // data.
1770         mExternalStylusDataPending = true;
1771         processRawTouches(false /*timeout*/);
1772     }
1773 }
1774 
consumeRawTouches(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)1775 bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
1776     // Check for release of a virtual key.
1777     if (mCurrentVirtualKey.down) {
1778         if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1779             // Pointer went up while virtual key was down.
1780             mCurrentVirtualKey.down = false;
1781             if (!mCurrentVirtualKey.ignored) {
1782 #if DEBUG_VIRTUAL_KEYS
1783                 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1784                       mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1785 #endif
1786                 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1787                                    AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1788             }
1789             return true;
1790         }
1791 
1792         if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1793             uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1794             const RawPointerData::Pointer& pointer =
1795                     mCurrentRawState.rawPointerData.pointerForId(id);
1796             const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1797             if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1798                 // Pointer is still within the space of the virtual key.
1799                 return true;
1800             }
1801         }
1802 
1803         // Pointer left virtual key area or another pointer also went down.
1804         // Send key cancellation but do not consume the touch yet.
1805         // This is useful when the user swipes through from the virtual key area
1806         // into the main display surface.
1807         mCurrentVirtualKey.down = false;
1808         if (!mCurrentVirtualKey.ignored) {
1809 #if DEBUG_VIRTUAL_KEYS
1810             ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1811                   mCurrentVirtualKey.scanCode);
1812 #endif
1813             dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1814                                AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1815                                        AKEY_EVENT_FLAG_CANCELED);
1816         }
1817     }
1818 
1819     if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1820         !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1821         // Pointer just went down.  Check for virtual key press or off-screen touches.
1822         uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1823         const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1824         // Exclude unscaled device for inside surface checking.
1825         if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
1826             // If exactly one pointer went down, check for virtual key hit.
1827             // Otherwise we will drop the entire stroke.
1828             if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1829                 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1830                 if (virtualKey) {
1831                     mCurrentVirtualKey.down = true;
1832                     mCurrentVirtualKey.downTime = when;
1833                     mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1834                     mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1835                     mCurrentVirtualKey.ignored =
1836                             getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1837                                                                virtualKey->scanCode);
1838 
1839                     if (!mCurrentVirtualKey.ignored) {
1840 #if DEBUG_VIRTUAL_KEYS
1841                         ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1842                               mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1843 #endif
1844                         dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
1845                                            AKEY_EVENT_FLAG_FROM_SYSTEM |
1846                                                    AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1847                     }
1848                 }
1849             }
1850             return true;
1851         }
1852     }
1853 
1854     // Disable all virtual key touches that happen within a short time interval of the
1855     // most recent touch within the screen area.  The idea is to filter out stray
1856     // virtual key presses when interacting with the touch screen.
1857     //
1858     // Problems we're trying to solve:
1859     //
1860     // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1861     //    virtual key area that is implemented by a separate touch panel and accidentally
1862     //    triggers a virtual key.
1863     //
1864     // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1865     //    area and accidentally triggers a virtual key.  This often happens when virtual keys
1866     //    are layed out below the screen near to where the on screen keyboard's space bar
1867     //    is displayed.
1868     if (mConfig.virtualKeyQuietTime > 0 &&
1869         !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1870         getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
1871     }
1872     return false;
1873 }
1874 
dispatchVirtualKey(nsecs_t when,nsecs_t readTime,uint32_t policyFlags,int32_t keyEventAction,int32_t keyEventFlags)1875 void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
1876                                           int32_t keyEventAction, int32_t keyEventFlags) {
1877     int32_t keyCode = mCurrentVirtualKey.keyCode;
1878     int32_t scanCode = mCurrentVirtualKey.scanCode;
1879     nsecs_t downTime = mCurrentVirtualKey.downTime;
1880     int32_t metaState = getContext()->getGlobalMetaState();
1881     policyFlags |= POLICY_FLAG_VIRTUAL;
1882 
1883     NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1884                        AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1885                        keyEventFlags, keyCode, scanCode, metaState, downTime);
1886     getListener()->notifyKey(&args);
1887 }
1888 
abortTouches(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)1889 void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
1890     BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1891     if (!currentIdBits.isEmpty()) {
1892         int32_t metaState = getContext()->getGlobalMetaState();
1893         int32_t buttonState = mCurrentCookedState.buttonState;
1894         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1895                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1896                        mCurrentCookedState.cookedPointerData.pointerProperties,
1897                        mCurrentCookedState.cookedPointerData.pointerCoords,
1898                        mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1899                        mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1900         mCurrentMotionAborted = true;
1901     }
1902 }
1903 
dispatchTouches(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)1904 void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
1905     BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1906     BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1907     int32_t metaState = getContext()->getGlobalMetaState();
1908     int32_t buttonState = mCurrentCookedState.buttonState;
1909 
1910     if (currentIdBits == lastIdBits) {
1911         if (!currentIdBits.isEmpty()) {
1912             // No pointer id changes so this is a move event.
1913             // The listener takes care of batching moves so we don't have to deal with that here.
1914             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1915                            metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1916                            mCurrentCookedState.cookedPointerData.pointerProperties,
1917                            mCurrentCookedState.cookedPointerData.pointerCoords,
1918                            mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1919                            mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1920         }
1921     } else {
1922         // There may be pointers going up and pointers going down and pointers moving
1923         // all at the same time.
1924         BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1925         BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1926         BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1927         BitSet32 dispatchedIdBits(lastIdBits.value);
1928 
1929         // Update last coordinates of pointers that have moved so that we observe the new
1930         // pointer positions at the same time as other pointers that have just gone up.
1931         bool moveNeeded =
1932                 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1933                                     mCurrentCookedState.cookedPointerData.pointerCoords,
1934                                     mCurrentCookedState.cookedPointerData.idToIndex,
1935                                     mLastCookedState.cookedPointerData.pointerProperties,
1936                                     mLastCookedState.cookedPointerData.pointerCoords,
1937                                     mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1938         if (buttonState != mLastCookedState.buttonState) {
1939             moveNeeded = true;
1940         }
1941 
1942         // Dispatch pointer up events.
1943         while (!upIdBits.isEmpty()) {
1944             uint32_t upId = upIdBits.clearFirstMarkedBit();
1945             bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1946             if (isCanceled) {
1947                 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1948             }
1949             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1950                            isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
1951                            mLastCookedState.cookedPointerData.pointerProperties,
1952                            mLastCookedState.cookedPointerData.pointerCoords,
1953                            mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1954                            mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1955             dispatchedIdBits.clearBit(upId);
1956             mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
1957         }
1958 
1959         // Dispatch move events if any of the remaining pointers moved from their old locations.
1960         // Although applications receive new locations as part of individual pointer up
1961         // events, they do not generally handle them except when presented in a move event.
1962         if (moveNeeded && !moveIdBits.isEmpty()) {
1963             ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1964             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1965                            metaState, buttonState, 0,
1966                            mCurrentCookedState.cookedPointerData.pointerProperties,
1967                            mCurrentCookedState.cookedPointerData.pointerCoords,
1968                            mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1969                            mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1970         }
1971 
1972         // Dispatch pointer down events using the new pointer locations.
1973         while (!downIdBits.isEmpty()) {
1974             uint32_t downId = downIdBits.clearFirstMarkedBit();
1975             dispatchedIdBits.markBit(downId);
1976 
1977             if (dispatchedIdBits.count() == 1) {
1978                 // First pointer is going down.  Set down time.
1979                 mDownTime = when;
1980             }
1981 
1982             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1983                            0, 0, metaState, buttonState, 0,
1984                            mCurrentCookedState.cookedPointerData.pointerProperties,
1985                            mCurrentCookedState.cookedPointerData.pointerCoords,
1986                            mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1987                            downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1988         }
1989     }
1990 }
1991 
dispatchHoverExit(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)1992 void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
1993     if (mSentHoverEnter &&
1994         (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1995          !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1996         int32_t metaState = getContext()->getGlobalMetaState();
1997         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
1998                        metaState, mLastCookedState.buttonState, 0,
1999                        mLastCookedState.cookedPointerData.pointerProperties,
2000                        mLastCookedState.cookedPointerData.pointerCoords,
2001                        mLastCookedState.cookedPointerData.idToIndex,
2002                        mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2003                        mOrientedYPrecision, mDownTime);
2004         mSentHoverEnter = false;
2005     }
2006 }
2007 
dispatchHoverEnterAndMove(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)2008 void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2009                                                  uint32_t policyFlags) {
2010     if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2011         !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2012         int32_t metaState = getContext()->getGlobalMetaState();
2013         if (!mSentHoverEnter) {
2014             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2015                            0, 0, metaState, mCurrentRawState.buttonState, 0,
2016                            mCurrentCookedState.cookedPointerData.pointerProperties,
2017                            mCurrentCookedState.cookedPointerData.pointerCoords,
2018                            mCurrentCookedState.cookedPointerData.idToIndex,
2019                            mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2020                            mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2021             mSentHoverEnter = true;
2022         }
2023 
2024         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2025                        metaState, mCurrentRawState.buttonState, 0,
2026                        mCurrentCookedState.cookedPointerData.pointerProperties,
2027                        mCurrentCookedState.cookedPointerData.pointerCoords,
2028                        mCurrentCookedState.cookedPointerData.idToIndex,
2029                        mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2030                        mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2031     }
2032 }
2033 
dispatchButtonRelease(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)2034 void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
2035     BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2036     const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2037     const int32_t metaState = getContext()->getGlobalMetaState();
2038     int32_t buttonState = mLastCookedState.buttonState;
2039     while (!releasedButtons.isEmpty()) {
2040         int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2041         buttonState &= ~actionButton;
2042         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2043                        actionButton, 0, metaState, buttonState, 0,
2044                        mCurrentCookedState.cookedPointerData.pointerProperties,
2045                        mCurrentCookedState.cookedPointerData.pointerCoords,
2046                        mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2047                        mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2048     }
2049 }
2050 
dispatchButtonPress(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)2051 void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
2052     BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2053     const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2054     const int32_t metaState = getContext()->getGlobalMetaState();
2055     int32_t buttonState = mLastCookedState.buttonState;
2056     while (!pressedButtons.isEmpty()) {
2057         int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2058         buttonState |= actionButton;
2059         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2060                        actionButton, 0, metaState, buttonState, 0,
2061                        mCurrentCookedState.cookedPointerData.pointerProperties,
2062                        mCurrentCookedState.cookedPointerData.pointerCoords,
2063                        mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2064                        mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2065     }
2066 }
2067 
findActiveIdBits(const CookedPointerData & cookedPointerData)2068 const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2069     if (!cookedPointerData.touchingIdBits.isEmpty()) {
2070         return cookedPointerData.touchingIdBits;
2071     }
2072     return cookedPointerData.hoveringIdBits;
2073 }
2074 
cookPointerData()2075 void TouchInputMapper::cookPointerData() {
2076     uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2077 
2078     mCurrentCookedState.cookedPointerData.clear();
2079     mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2080     mCurrentCookedState.cookedPointerData.hoveringIdBits =
2081             mCurrentRawState.rawPointerData.hoveringIdBits;
2082     mCurrentCookedState.cookedPointerData.touchingIdBits =
2083             mCurrentRawState.rawPointerData.touchingIdBits;
2084     mCurrentCookedState.cookedPointerData.canceledIdBits =
2085             mCurrentRawState.rawPointerData.canceledIdBits;
2086 
2087     if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2088         mCurrentCookedState.buttonState = 0;
2089     } else {
2090         mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2091     }
2092 
2093     // Walk through the the active pointers and map device coordinates onto
2094     // surface coordinates and adjust for display orientation.
2095     for (uint32_t i = 0; i < currentPointerCount; i++) {
2096         const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2097 
2098         // Size
2099         float touchMajor, touchMinor, toolMajor, toolMinor, size;
2100         switch (mCalibration.sizeCalibration) {
2101             case Calibration::SizeCalibration::GEOMETRIC:
2102             case Calibration::SizeCalibration::DIAMETER:
2103             case Calibration::SizeCalibration::BOX:
2104             case Calibration::SizeCalibration::AREA:
2105                 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2106                     touchMajor = in.touchMajor;
2107                     touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2108                     toolMajor = in.toolMajor;
2109                     toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2110                     size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2111                                                             : in.touchMajor;
2112                 } else if (mRawPointerAxes.touchMajor.valid) {
2113                     toolMajor = touchMajor = in.touchMajor;
2114                     toolMinor = touchMinor =
2115                             mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2116                     size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2117                                                             : in.touchMajor;
2118                 } else if (mRawPointerAxes.toolMajor.valid) {
2119                     touchMajor = toolMajor = in.toolMajor;
2120                     touchMinor = toolMinor =
2121                             mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2122                     size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2123                                                            : in.toolMajor;
2124                 } else {
2125                     ALOG_ASSERT(false,
2126                                 "No touch or tool axes.  "
2127                                 "Size calibration should have been resolved to NONE.");
2128                     touchMajor = 0;
2129                     touchMinor = 0;
2130                     toolMajor = 0;
2131                     toolMinor = 0;
2132                     size = 0;
2133                 }
2134 
2135                 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2136                     uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2137                     if (touchingCount > 1) {
2138                         touchMajor /= touchingCount;
2139                         touchMinor /= touchingCount;
2140                         toolMajor /= touchingCount;
2141                         toolMinor /= touchingCount;
2142                         size /= touchingCount;
2143                     }
2144                 }
2145 
2146                 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
2147                     touchMajor *= mGeometricScale;
2148                     touchMinor *= mGeometricScale;
2149                     toolMajor *= mGeometricScale;
2150                     toolMinor *= mGeometricScale;
2151                 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
2152                     touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2153                     touchMinor = touchMajor;
2154                     toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2155                     toolMinor = toolMajor;
2156                 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
2157                     touchMinor = touchMajor;
2158                     toolMinor = toolMajor;
2159                 }
2160 
2161                 mCalibration.applySizeScaleAndBias(&touchMajor);
2162                 mCalibration.applySizeScaleAndBias(&touchMinor);
2163                 mCalibration.applySizeScaleAndBias(&toolMajor);
2164                 mCalibration.applySizeScaleAndBias(&toolMinor);
2165                 size *= mSizeScale;
2166                 break;
2167             default:
2168                 touchMajor = 0;
2169                 touchMinor = 0;
2170                 toolMajor = 0;
2171                 toolMinor = 0;
2172                 size = 0;
2173                 break;
2174         }
2175 
2176         // Pressure
2177         float pressure;
2178         switch (mCalibration.pressureCalibration) {
2179             case Calibration::PressureCalibration::PHYSICAL:
2180             case Calibration::PressureCalibration::AMPLITUDE:
2181                 pressure = in.pressure * mPressureScale;
2182                 break;
2183             default:
2184                 pressure = in.isHovering ? 0 : 1;
2185                 break;
2186         }
2187 
2188         // Tilt and Orientation
2189         float tilt;
2190         float orientation;
2191         if (mHaveTilt) {
2192             float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2193             float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2194             orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2195             tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2196         } else {
2197             tilt = 0;
2198 
2199             switch (mCalibration.orientationCalibration) {
2200                 case Calibration::OrientationCalibration::INTERPOLATED:
2201                     orientation = in.orientation * mOrientationScale;
2202                     break;
2203                 case Calibration::OrientationCalibration::VECTOR: {
2204                     int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2205                     int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2206                     if (c1 != 0 || c2 != 0) {
2207                         orientation = atan2f(c1, c2) * 0.5f;
2208                         float confidence = hypotf(c1, c2);
2209                         float scale = 1.0f + confidence / 16.0f;
2210                         touchMajor *= scale;
2211                         touchMinor /= scale;
2212                         toolMajor *= scale;
2213                         toolMinor /= scale;
2214                     } else {
2215                         orientation = 0;
2216                     }
2217                     break;
2218                 }
2219                 default:
2220                     orientation = 0;
2221             }
2222         }
2223 
2224         // Distance
2225         float distance;
2226         switch (mCalibration.distanceCalibration) {
2227             case Calibration::DistanceCalibration::SCALED:
2228                 distance = in.distance * mDistanceScale;
2229                 break;
2230             default:
2231                 distance = 0;
2232         }
2233 
2234         // Coverage
2235         int32_t rawLeft, rawTop, rawRight, rawBottom;
2236         switch (mCalibration.coverageCalibration) {
2237             case Calibration::CoverageCalibration::BOX:
2238                 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2239                 rawRight = in.toolMinor & 0x0000ffff;
2240                 rawBottom = in.toolMajor & 0x0000ffff;
2241                 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2242                 break;
2243             default:
2244                 rawLeft = rawTop = rawRight = rawBottom = 0;
2245                 break;
2246         }
2247 
2248         // Adjust X,Y coords for device calibration
2249         // TODO: Adjust coverage coords?
2250         float xTransformed = in.x, yTransformed = in.y;
2251         mAffineTransform.applyTo(xTransformed, yTransformed);
2252         rotateAndScale(xTransformed, yTransformed);
2253 
2254         // Adjust X, Y, and coverage coords for surface orientation.
2255         float left, top, right, bottom;
2256 
2257         switch (mSurfaceOrientation) {
2258             case DISPLAY_ORIENTATION_90:
2259                 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2260                 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2261                 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2262                 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2263                 orientation -= M_PI_2;
2264                 if (mOrientedRanges.haveOrientation &&
2265                     orientation < mOrientedRanges.orientation.min) {
2266                     orientation +=
2267                             (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2268                 }
2269                 break;
2270             case DISPLAY_ORIENTATION_180:
2271                 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2272                 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2273                 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2274                 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2275                 orientation -= M_PI;
2276                 if (mOrientedRanges.haveOrientation &&
2277                     orientation < mOrientedRanges.orientation.min) {
2278                     orientation +=
2279                             (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2280                 }
2281                 break;
2282             case DISPLAY_ORIENTATION_270:
2283                 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2284                 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2285                 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2286                 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2287                 orientation += M_PI_2;
2288                 if (mOrientedRanges.haveOrientation &&
2289                     orientation > mOrientedRanges.orientation.max) {
2290                     orientation -=
2291                             (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2292                 }
2293                 break;
2294             default:
2295                 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2296                 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2297                 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2298                 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2299                 break;
2300         }
2301 
2302         // Write output coords.
2303         PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2304         out.clear();
2305         out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2306         out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
2307         out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2308         out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2309         out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2310         out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2311         out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2312         out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2313         out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
2314         if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
2315             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2316             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2317             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2318             out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2319         } else {
2320             out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2321             out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2322         }
2323 
2324         // Write output relative fields if applicable.
2325         uint32_t id = in.id;
2326         if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2327             mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2328             const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2329             float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2330             float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2331             out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2332             out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2333         }
2334 
2335         // Write output properties.
2336         PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
2337         properties.clear();
2338         properties.id = id;
2339         properties.toolType = in.toolType;
2340 
2341         // Write id index and mark id as valid.
2342         mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
2343         mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
2344     }
2345 }
2346 
dispatchPointerUsage(nsecs_t when,nsecs_t readTime,uint32_t policyFlags,PointerUsage pointerUsage)2347 void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2348                                             PointerUsage pointerUsage) {
2349     if (pointerUsage != mPointerUsage) {
2350         abortPointerUsage(when, readTime, policyFlags);
2351         mPointerUsage = pointerUsage;
2352     }
2353 
2354     switch (mPointerUsage) {
2355         case PointerUsage::GESTURES:
2356             dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
2357             break;
2358         case PointerUsage::STYLUS:
2359             dispatchPointerStylus(when, readTime, policyFlags);
2360             break;
2361         case PointerUsage::MOUSE:
2362             dispatchPointerMouse(when, readTime, policyFlags);
2363             break;
2364         case PointerUsage::NONE:
2365             break;
2366     }
2367 }
2368 
abortPointerUsage(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)2369 void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
2370     switch (mPointerUsage) {
2371         case PointerUsage::GESTURES:
2372             abortPointerGestures(when, readTime, policyFlags);
2373             break;
2374         case PointerUsage::STYLUS:
2375             abortPointerStylus(when, readTime, policyFlags);
2376             break;
2377         case PointerUsage::MOUSE:
2378             abortPointerMouse(when, readTime, policyFlags);
2379             break;
2380         case PointerUsage::NONE:
2381             break;
2382     }
2383 
2384     mPointerUsage = PointerUsage::NONE;
2385 }
2386 
dispatchPointerGestures(nsecs_t when,nsecs_t readTime,uint32_t policyFlags,bool isTimeout)2387 void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2388                                                bool isTimeout) {
2389     // Update current gesture coordinates.
2390     bool cancelPreviousGesture, finishPreviousGesture;
2391     bool sendEvents =
2392             preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2393     if (!sendEvents) {
2394         return;
2395     }
2396     if (finishPreviousGesture) {
2397         cancelPreviousGesture = false;
2398     }
2399 
2400     // Update the pointer presentation and spots.
2401     if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
2402         mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
2403         if (finishPreviousGesture || cancelPreviousGesture) {
2404             mPointerController->clearSpots();
2405         }
2406 
2407         if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
2408             setTouchSpots(mPointerGesture.currentGestureCoords,
2409                           mPointerGesture.currentGestureIdToIndex,
2410                           mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
2411         }
2412     } else {
2413         mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
2414     }
2415 
2416     // Show or hide the pointer if needed.
2417     switch (mPointerGesture.currentGestureMode) {
2418         case PointerGesture::Mode::NEUTRAL:
2419         case PointerGesture::Mode::QUIET:
2420             if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2421                 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
2422                 // Remind the user of where the pointer is after finishing a gesture with spots.
2423                 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
2424             }
2425             break;
2426         case PointerGesture::Mode::TAP:
2427         case PointerGesture::Mode::TAP_DRAG:
2428         case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2429         case PointerGesture::Mode::HOVER:
2430         case PointerGesture::Mode::PRESS:
2431         case PointerGesture::Mode::SWIPE:
2432             // Unfade the pointer when the current gesture manipulates the
2433             // area directly under the pointer.
2434             mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
2435             break;
2436         case PointerGesture::Mode::FREEFORM:
2437             // Fade the pointer when the current gesture manipulates a different
2438             // area and there are spots to guide the user experience.
2439             if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
2440                 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
2441             } else {
2442                 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
2443             }
2444             break;
2445     }
2446 
2447     // Send events!
2448     int32_t metaState = getContext()->getGlobalMetaState();
2449     int32_t buttonState = mCurrentCookedState.buttonState;
2450 
2451     uint32_t flags = 0;
2452 
2453     if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2454         flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2455     }
2456 
2457     // Update last coordinates of pointers that have moved so that we observe the new
2458     // pointer positions at the same time as other pointers that have just gone up.
2459     bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2460             mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2461             mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2462             mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2463             mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2464             mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
2465     bool moveNeeded = false;
2466     if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2467         !mPointerGesture.lastGestureIdBits.isEmpty() &&
2468         !mPointerGesture.currentGestureIdBits.isEmpty()) {
2469         BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2470                                     mPointerGesture.lastGestureIdBits.value);
2471         moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2472                                          mPointerGesture.currentGestureCoords,
2473                                          mPointerGesture.currentGestureIdToIndex,
2474                                          mPointerGesture.lastGestureProperties,
2475                                          mPointerGesture.lastGestureCoords,
2476                                          mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2477         if (buttonState != mLastCookedState.buttonState) {
2478             moveNeeded = true;
2479         }
2480     }
2481 
2482     // Send motion events for all pointers that went up or were canceled.
2483     BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2484     if (!dispatchedGestureIdBits.isEmpty()) {
2485         if (cancelPreviousGesture) {
2486             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2487                            flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2488                            mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2489                            mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2490                            mPointerGesture.downTime);
2491 
2492             dispatchedGestureIdBits.clear();
2493         } else {
2494             BitSet32 upGestureIdBits;
2495             if (finishPreviousGesture) {
2496                 upGestureIdBits = dispatchedGestureIdBits;
2497             } else {
2498                 upGestureIdBits.value =
2499                         dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2500             }
2501             while (!upGestureIdBits.isEmpty()) {
2502                 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2503 
2504                 dispatchMotion(when, readTime, policyFlags, mSource,
2505                                AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
2506                                AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
2507                                mPointerGesture.lastGestureCoords,
2508                                mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2509                                0, mPointerGesture.downTime);
2510 
2511                 dispatchedGestureIdBits.clearBit(id);
2512             }
2513         }
2514     }
2515 
2516     // Send motion events for all pointers that moved.
2517     if (moveNeeded) {
2518         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
2519                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2520                        mPointerGesture.currentGestureProperties,
2521                        mPointerGesture.currentGestureCoords,
2522                        mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2523                        mPointerGesture.downTime);
2524     }
2525 
2526     // Send motion events for all pointers that went down.
2527     if (down) {
2528         BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2529                                    ~dispatchedGestureIdBits.value);
2530         while (!downGestureIdBits.isEmpty()) {
2531             uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2532             dispatchedGestureIdBits.markBit(id);
2533 
2534             if (dispatchedGestureIdBits.count() == 1) {
2535                 mPointerGesture.downTime = when;
2536             }
2537 
2538             dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2539                            0, flags, metaState, buttonState, 0,
2540                            mPointerGesture.currentGestureProperties,
2541                            mPointerGesture.currentGestureCoords,
2542                            mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2543                            0, mPointerGesture.downTime);
2544         }
2545     }
2546 
2547     // Send motion events for hover.
2548     if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
2549         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2550                        flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2551                        mPointerGesture.currentGestureProperties,
2552                        mPointerGesture.currentGestureCoords,
2553                        mPointerGesture.currentGestureIdToIndex,
2554                        mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2555     } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2556         // Synthesize a hover move event after all pointers go up to indicate that
2557         // the pointer is hovering again even if the user is not currently touching
2558         // the touch pad.  This ensures that a view will receive a fresh hover enter
2559         // event after a tap.
2560         auto [x, y] = getMouseCursorPosition();
2561 
2562         PointerProperties pointerProperties;
2563         pointerProperties.clear();
2564         pointerProperties.id = 0;
2565         pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2566 
2567         PointerCoords pointerCoords;
2568         pointerCoords.clear();
2569         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2570         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2571 
2572         const int32_t displayId = mPointerController->getDisplayId();
2573         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
2574                               displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
2575                               metaState, buttonState, MotionClassification::NONE,
2576                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2577                               0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
2578         getListener()->notifyMotion(&args);
2579     }
2580 
2581     // Update state.
2582     mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2583     if (!down) {
2584         mPointerGesture.lastGestureIdBits.clear();
2585     } else {
2586         mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2587         for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2588             uint32_t id = idBits.clearFirstMarkedBit();
2589             uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2590             mPointerGesture.lastGestureProperties[index].copyFrom(
2591                     mPointerGesture.currentGestureProperties[index]);
2592             mPointerGesture.lastGestureCoords[index].copyFrom(
2593                     mPointerGesture.currentGestureCoords[index]);
2594             mPointerGesture.lastGestureIdToIndex[id] = index;
2595         }
2596     }
2597 }
2598 
abortPointerGestures(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)2599 void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
2600     // Cancel previously dispatches pointers.
2601     if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2602         int32_t metaState = getContext()->getGlobalMetaState();
2603         int32_t buttonState = mCurrentRawState.buttonState;
2604         dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2605                        metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2606                        mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2607                        mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2608                        0, 0, mPointerGesture.downTime);
2609     }
2610 
2611     // Reset the current pointer gesture.
2612     mPointerGesture.reset();
2613     mPointerVelocityControl.reset();
2614 
2615     // Remove any current spots.
2616     if (mPointerController != nullptr) {
2617         mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
2618         mPointerController->clearSpots();
2619     }
2620 }
2621 
preparePointerGestures(nsecs_t when,bool * outCancelPreviousGesture,bool * outFinishPreviousGesture,bool isTimeout)2622 bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2623                                               bool* outFinishPreviousGesture, bool isTimeout) {
2624     *outCancelPreviousGesture = false;
2625     *outFinishPreviousGesture = false;
2626 
2627     // Handle TAP timeout.
2628     if (isTimeout) {
2629 #if DEBUG_GESTURES
2630         ALOGD("Gestures: Processing timeout");
2631 #endif
2632 
2633         if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
2634             if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2635                 // The tap/drag timeout has not yet expired.
2636                 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2637                                                    mConfig.pointerGestureTapDragInterval);
2638             } else {
2639                 // The tap is finished.
2640 #if DEBUG_GESTURES
2641                 ALOGD("Gestures: TAP finished");
2642 #endif
2643                 *outFinishPreviousGesture = true;
2644 
2645                 mPointerGesture.activeGestureId = -1;
2646                 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
2647                 mPointerGesture.currentGestureIdBits.clear();
2648 
2649                 mPointerVelocityControl.reset();
2650                 return true;
2651             }
2652         }
2653 
2654         // We did not handle this timeout.
2655         return false;
2656     }
2657 
2658     const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2659     const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2660 
2661     // Update the velocity tracker.
2662     {
2663         std::vector<VelocityTracker::Position> positions;
2664         for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2665             uint32_t id = idBits.clearFirstMarkedBit();
2666             const RawPointerData::Pointer& pointer =
2667                     mCurrentRawState.rawPointerData.pointerForId(id);
2668             float x = pointer.x * mPointerXMovementScale;
2669             float y = pointer.y * mPointerYMovementScale;
2670             positions.push_back({x, y});
2671         }
2672         mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2673                                                     positions);
2674     }
2675 
2676     // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2677     // to NEUTRAL, then we should not generate tap event.
2678     if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2679         mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2680         mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
2681         mPointerGesture.resetTap();
2682     }
2683 
2684     // Pick a new active touch id if needed.
2685     // Choose an arbitrary pointer that just went down, if there is one.
2686     // Otherwise choose an arbitrary remaining pointer.
2687     // This guarantees we always have an active touch id when there is at least one pointer.
2688     // We keep the same active touch id for as long as possible.
2689     int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2690     int32_t activeTouchId = lastActiveTouchId;
2691     if (activeTouchId < 0) {
2692         if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2693             activeTouchId = mPointerGesture.activeTouchId =
2694                     mCurrentCookedState.fingerIdBits.firstMarkedBit();
2695             mPointerGesture.firstTouchTime = when;
2696         }
2697     } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2698         if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2699             activeTouchId = mPointerGesture.activeTouchId =
2700                     mCurrentCookedState.fingerIdBits.firstMarkedBit();
2701         } else {
2702             activeTouchId = mPointerGesture.activeTouchId = -1;
2703         }
2704     }
2705 
2706     // Determine whether we are in quiet time.
2707     bool isQuietTime = false;
2708     if (activeTouchId < 0) {
2709         mPointerGesture.resetQuietTime();
2710     } else {
2711         isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2712         if (!isQuietTime) {
2713             if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2714                  mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2715                  mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
2716                 currentFingerCount < 2) {
2717                 // Enter quiet time when exiting swipe or freeform state.
2718                 // This is to prevent accidentally entering the hover state and flinging the
2719                 // pointer when finishing a swipe and there is still one pointer left onscreen.
2720                 isQuietTime = true;
2721             } else if (mPointerGesture.lastGestureMode ==
2722                                PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
2723                        currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2724                 // Enter quiet time when releasing the button and there are still two or more
2725                 // fingers down.  This may indicate that one finger was used to press the button
2726                 // but it has not gone up yet.
2727                 isQuietTime = true;
2728             }
2729             if (isQuietTime) {
2730                 mPointerGesture.quietTime = when;
2731             }
2732         }
2733     }
2734 
2735     // Switch states based on button and pointer state.
2736     if (isQuietTime) {
2737         // Case 1: Quiet time. (QUIET)
2738 #if DEBUG_GESTURES
2739         ALOGD("Gestures: QUIET for next %0.3fms",
2740               (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2741 #endif
2742         if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
2743             *outFinishPreviousGesture = true;
2744         }
2745 
2746         mPointerGesture.activeGestureId = -1;
2747         mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
2748         mPointerGesture.currentGestureIdBits.clear();
2749 
2750         mPointerVelocityControl.reset();
2751     } else if (isPointerDown(mCurrentRawState.buttonState)) {
2752         // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2753         // The pointer follows the active touch point.
2754         // Emit DOWN, MOVE, UP events at the pointer location.
2755         //
2756         // Only the active touch matters; other fingers are ignored.  This policy helps
2757         // to handle the case where the user places a second finger on the touch pad
2758         // to apply the necessary force to depress an integrated button below the surface.
2759         // We don't want the second finger to be delivered to applications.
2760         //
2761         // For this to work well, we need to make sure to track the pointer that is really
2762         // active.  If the user first puts one finger down to click then adds another
2763         // finger to drag then the active pointer should switch to the finger that is
2764         // being dragged.
2765 #if DEBUG_GESTURES
2766         ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2767               "currentFingerCount=%d",
2768               activeTouchId, currentFingerCount);
2769 #endif
2770         // Reset state when just starting.
2771         if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2772             *outFinishPreviousGesture = true;
2773             mPointerGesture.activeGestureId = 0;
2774         }
2775 
2776         // Switch pointers if needed.
2777         // Find the fastest pointer and follow it.
2778         if (activeTouchId >= 0 && currentFingerCount > 1) {
2779             int32_t bestId = -1;
2780             float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2781             for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2782                 uint32_t id = idBits.clearFirstMarkedBit();
2783                 float vx, vy;
2784                 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2785                     float speed = hypotf(vx, vy);
2786                     if (speed > bestSpeed) {
2787                         bestId = id;
2788                         bestSpeed = speed;
2789                     }
2790                 }
2791             }
2792             if (bestId >= 0 && bestId != activeTouchId) {
2793                 mPointerGesture.activeTouchId = activeTouchId = bestId;
2794 #if DEBUG_GESTURES
2795                 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2796                       "bestId=%d, bestSpeed=%0.3f",
2797                       bestId, bestSpeed);
2798 #endif
2799             }
2800         }
2801 
2802         float deltaX = 0, deltaY = 0;
2803         if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2804             const RawPointerData::Pointer& currentPointer =
2805                     mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2806             const RawPointerData::Pointer& lastPointer =
2807                     mLastRawState.rawPointerData.pointerForId(activeTouchId);
2808             deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2809             deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2810 
2811             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2812             mPointerVelocityControl.move(when, &deltaX, &deltaY);
2813 
2814             // Move the pointer using a relative motion.
2815             // When using spots, the click will occur at the position of the anchor
2816             // spot and all other spots will move there.
2817             moveMouseCursor(deltaX, deltaY);
2818         } else {
2819             mPointerVelocityControl.reset();
2820         }
2821 
2822         auto [x, y] = getMouseCursorPosition();
2823 
2824         mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
2825         mPointerGesture.currentGestureIdBits.clear();
2826         mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2827         mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2828         mPointerGesture.currentGestureProperties[0].clear();
2829         mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2830         mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2831         mPointerGesture.currentGestureCoords[0].clear();
2832         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2833         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2834         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2835     } else if (currentFingerCount == 0) {
2836         // Case 3. No fingers down and button is not pressed. (NEUTRAL)
2837         if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
2838             *outFinishPreviousGesture = true;
2839         }
2840 
2841         // Watch for taps coming out of HOVER or TAP_DRAG mode.
2842         // Checking for taps after TAP_DRAG allows us to detect double-taps.
2843         bool tapped = false;
2844         if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2845              mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
2846             lastFingerCount == 1) {
2847             if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2848                 auto [x, y] = getMouseCursorPosition();
2849                 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2850                     fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2851 #if DEBUG_GESTURES
2852                     ALOGD("Gestures: TAP");
2853 #endif
2854 
2855                     mPointerGesture.tapUpTime = when;
2856                     getContext()->requestTimeoutAtTime(when +
2857                                                        mConfig.pointerGestureTapDragInterval);
2858 
2859                     mPointerGesture.activeGestureId = 0;
2860                     mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
2861                     mPointerGesture.currentGestureIdBits.clear();
2862                     mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2863                     mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2864                     mPointerGesture.currentGestureProperties[0].clear();
2865                     mPointerGesture.currentGestureProperties[0].id =
2866                             mPointerGesture.activeGestureId;
2867                     mPointerGesture.currentGestureProperties[0].toolType =
2868                             AMOTION_EVENT_TOOL_TYPE_FINGER;
2869                     mPointerGesture.currentGestureCoords[0].clear();
2870                     mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2871                                                                          mPointerGesture.tapX);
2872                     mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2873                                                                          mPointerGesture.tapY);
2874                     mPointerGesture.currentGestureCoords[0]
2875                             .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2876 
2877                     tapped = true;
2878                 } else {
2879 #if DEBUG_GESTURES
2880                     ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2881                           y - mPointerGesture.tapY);
2882 #endif
2883                 }
2884             } else {
2885 #if DEBUG_GESTURES
2886                 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2887                     ALOGD("Gestures: Not a TAP, %0.3fms since down",
2888                           (when - mPointerGesture.tapDownTime) * 0.000001f);
2889                 } else {
2890                     ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2891                 }
2892 #endif
2893             }
2894         }
2895 
2896         mPointerVelocityControl.reset();
2897 
2898         if (!tapped) {
2899 #if DEBUG_GESTURES
2900             ALOGD("Gestures: NEUTRAL");
2901 #endif
2902             mPointerGesture.activeGestureId = -1;
2903             mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
2904             mPointerGesture.currentGestureIdBits.clear();
2905         }
2906     } else if (currentFingerCount == 1) {
2907         // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2908         // The pointer follows the active touch point.
2909         // When in HOVER, emit HOVER_MOVE events at the pointer location.
2910         // When in TAP_DRAG, emit MOVE events at the pointer location.
2911         ALOG_ASSERT(activeTouchId >= 0);
2912 
2913         mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2914         if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
2915             if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2916                 auto [x, y] = getMouseCursorPosition();
2917                 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2918                     fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2919                     mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
2920                 } else {
2921 #if DEBUG_GESTURES
2922                     ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2923                           x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2924 #endif
2925                 }
2926             } else {
2927 #if DEBUG_GESTURES
2928                 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2929                       (when - mPointerGesture.tapUpTime) * 0.000001f);
2930 #endif
2931             }
2932         } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2933             mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
2934         }
2935 
2936         float deltaX = 0, deltaY = 0;
2937         if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2938             const RawPointerData::Pointer& currentPointer =
2939                     mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2940             const RawPointerData::Pointer& lastPointer =
2941                     mLastRawState.rawPointerData.pointerForId(activeTouchId);
2942             deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2943             deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2944 
2945             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2946             mPointerVelocityControl.move(when, &deltaX, &deltaY);
2947 
2948             // Move the pointer using a relative motion.
2949             // When using spots, the hover or drag will occur at the position of the anchor spot.
2950             moveMouseCursor(deltaX, deltaY);
2951         } else {
2952             mPointerVelocityControl.reset();
2953         }
2954 
2955         bool down;
2956         if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
2957 #if DEBUG_GESTURES
2958             ALOGD("Gestures: TAP_DRAG");
2959 #endif
2960             down = true;
2961         } else {
2962 #if DEBUG_GESTURES
2963             ALOGD("Gestures: HOVER");
2964 #endif
2965             if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
2966                 *outFinishPreviousGesture = true;
2967             }
2968             mPointerGesture.activeGestureId = 0;
2969             down = false;
2970         }
2971 
2972         auto [x, y] = getMouseCursorPosition();
2973 
2974         mPointerGesture.currentGestureIdBits.clear();
2975         mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2976         mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2977         mPointerGesture.currentGestureProperties[0].clear();
2978         mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2979         mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2980         mPointerGesture.currentGestureCoords[0].clear();
2981         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2982         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2983         mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2984                                                              down ? 1.0f : 0.0f);
2985 
2986         if (lastFingerCount == 0 && currentFingerCount != 0) {
2987             mPointerGesture.resetTap();
2988             mPointerGesture.tapDownTime = when;
2989             mPointerGesture.tapX = x;
2990             mPointerGesture.tapY = y;
2991         }
2992     } else {
2993         // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2994         // We need to provide feedback for each finger that goes down so we cannot wait
2995         // for the fingers to move before deciding what to do.
2996         //
2997         // The ambiguous case is deciding what to do when there are two fingers down but they
2998         // have not moved enough to determine whether they are part of a drag or part of a
2999         // freeform gesture, or just a press or long-press at the pointer location.
3000         //
3001         // When there are two fingers we start with the PRESS hypothesis and we generate a
3002         // down at the pointer location.
3003         //
3004         // When the two fingers move enough or when additional fingers are added, we make
3005         // a decision to transition into SWIPE or FREEFORM mode accordingly.
3006         ALOG_ASSERT(activeTouchId >= 0);
3007 
3008         bool settled = when >=
3009                 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3010         if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3011             mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3012             mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3013             *outFinishPreviousGesture = true;
3014         } else if (!settled && currentFingerCount > lastFingerCount) {
3015             // Additional pointers have gone down but not yet settled.
3016             // Reset the gesture.
3017 #if DEBUG_GESTURES
3018             ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3019                   "settle time remaining %0.3fms",
3020                   (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3021                    when) * 0.000001f);
3022 #endif
3023             *outCancelPreviousGesture = true;
3024         } else {
3025             // Continue previous gesture.
3026             mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3027         }
3028 
3029         if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
3030             mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3031             mPointerGesture.activeGestureId = 0;
3032             mPointerGesture.referenceIdBits.clear();
3033             mPointerVelocityControl.reset();
3034 
3035             // Use the centroid and pointer location as the reference points for the gesture.
3036 #if DEBUG_GESTURES
3037             ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3038                   "settle time remaining %0.3fms",
3039                   (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3040                    when) * 0.000001f);
3041 #endif
3042             mCurrentRawState.rawPointerData
3043                     .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3044                                                    &mPointerGesture.referenceTouchY);
3045             auto [x, y] = getMouseCursorPosition();
3046             mPointerGesture.referenceGestureX = x;
3047             mPointerGesture.referenceGestureY = y;
3048         }
3049 
3050         // Clear the reference deltas for fingers not yet included in the reference calculation.
3051         for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3052                              ~mPointerGesture.referenceIdBits.value);
3053              !idBits.isEmpty();) {
3054             uint32_t id = idBits.clearFirstMarkedBit();
3055             mPointerGesture.referenceDeltas[id].dx = 0;
3056             mPointerGesture.referenceDeltas[id].dy = 0;
3057         }
3058         mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3059 
3060         // Add delta for all fingers and calculate a common movement delta.
3061         float commonDeltaX = 0, commonDeltaY = 0;
3062         BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3063                               mCurrentCookedState.fingerIdBits.value);
3064         for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3065             bool first = (idBits == commonIdBits);
3066             uint32_t id = idBits.clearFirstMarkedBit();
3067             const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3068             const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3069             PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3070             delta.dx += cpd.x - lpd.x;
3071             delta.dy += cpd.y - lpd.y;
3072 
3073             if (first) {
3074                 commonDeltaX = delta.dx;
3075                 commonDeltaY = delta.dy;
3076             } else {
3077                 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3078                 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3079             }
3080         }
3081 
3082         // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3083         if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3084             float dist[MAX_POINTER_ID + 1];
3085             int32_t distOverThreshold = 0;
3086             for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3087                 uint32_t id = idBits.clearFirstMarkedBit();
3088                 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3089                 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3090                 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3091                     distOverThreshold += 1;
3092                 }
3093             }
3094 
3095             // Only transition when at least two pointers have moved further than
3096             // the minimum distance threshold.
3097             if (distOverThreshold >= 2) {
3098                 if (currentFingerCount > 2) {
3099                     // There are more than two pointers, switch to FREEFORM.
3100 #if DEBUG_GESTURES
3101                     ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3102                           currentFingerCount);
3103 #endif
3104                     *outCancelPreviousGesture = true;
3105                     mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3106                 } else {
3107                     // There are exactly two pointers.
3108                     BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3109                     uint32_t id1 = idBits.clearFirstMarkedBit();
3110                     uint32_t id2 = idBits.firstMarkedBit();
3111                     const RawPointerData::Pointer& p1 =
3112                             mCurrentRawState.rawPointerData.pointerForId(id1);
3113                     const RawPointerData::Pointer& p2 =
3114                             mCurrentRawState.rawPointerData.pointerForId(id2);
3115                     float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3116                     if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3117                         // There are two pointers but they are too far apart for a SWIPE,
3118                         // switch to FREEFORM.
3119 #if DEBUG_GESTURES
3120                         ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3121                               mutualDistance, mPointerGestureMaxSwipeWidth);
3122 #endif
3123                         *outCancelPreviousGesture = true;
3124                         mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3125                     } else {
3126                         // There are two pointers.  Wait for both pointers to start moving
3127                         // before deciding whether this is a SWIPE or FREEFORM gesture.
3128                         float dist1 = dist[id1];
3129                         float dist2 = dist[id2];
3130                         if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3131                             dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3132                             // Calculate the dot product of the displacement vectors.
3133                             // When the vectors are oriented in approximately the same direction,
3134                             // the angle betweeen them is near zero and the cosine of the angle
3135                             // approches 1.0.  Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3136                             // mag(v2).
3137                             PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3138                             PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3139                             float dx1 = delta1.dx * mPointerXZoomScale;
3140                             float dy1 = delta1.dy * mPointerYZoomScale;
3141                             float dx2 = delta2.dx * mPointerXZoomScale;
3142                             float dy2 = delta2.dy * mPointerYZoomScale;
3143                             float dot = dx1 * dx2 + dy1 * dy2;
3144                             float cosine = dot / (dist1 * dist2); // denominator always > 0
3145                             if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3146                                 // Pointers are moving in the same direction.  Switch to SWIPE.
3147 #if DEBUG_GESTURES
3148                                 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3149                                       "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3150                                       "cosine %0.3f >= %0.3f",
3151                                       dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3152                                       mConfig.pointerGestureMultitouchMinDistance, cosine,
3153                                       mConfig.pointerGestureSwipeTransitionAngleCosine);
3154 #endif
3155                                 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3156                             } else {
3157                                 // Pointers are moving in different directions.  Switch to FREEFORM.
3158 #if DEBUG_GESTURES
3159                                 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3160                                       "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3161                                       "cosine %0.3f < %0.3f",
3162                                       dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3163                                       mConfig.pointerGestureMultitouchMinDistance, cosine,
3164                                       mConfig.pointerGestureSwipeTransitionAngleCosine);
3165 #endif
3166                                 *outCancelPreviousGesture = true;
3167                                 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3168                             }
3169                         }
3170                     }
3171                 }
3172             }
3173         } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3174             // Switch from SWIPE to FREEFORM if additional pointers go down.
3175             // Cancel previous gesture.
3176             if (currentFingerCount > 2) {
3177 #if DEBUG_GESTURES
3178                 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3179                       currentFingerCount);
3180 #endif
3181                 *outCancelPreviousGesture = true;
3182                 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3183             }
3184         }
3185 
3186         // Move the reference points based on the overall group motion of the fingers
3187         // except in PRESS mode while waiting for a transition to occur.
3188         if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3189             (commonDeltaX || commonDeltaY)) {
3190             for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3191                 uint32_t id = idBits.clearFirstMarkedBit();
3192                 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3193                 delta.dx = 0;
3194                 delta.dy = 0;
3195             }
3196 
3197             mPointerGesture.referenceTouchX += commonDeltaX;
3198             mPointerGesture.referenceTouchY += commonDeltaY;
3199 
3200             commonDeltaX *= mPointerXMovementScale;
3201             commonDeltaY *= mPointerYMovementScale;
3202 
3203             rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3204             mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3205 
3206             mPointerGesture.referenceGestureX += commonDeltaX;
3207             mPointerGesture.referenceGestureY += commonDeltaY;
3208         }
3209 
3210         // Report gestures.
3211         if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3212             mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3213             // PRESS or SWIPE mode.
3214 #if DEBUG_GESTURES
3215             ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3216                   "activeGestureId=%d, currentTouchPointerCount=%d",
3217                   activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3218 #endif
3219             ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3220 
3221             mPointerGesture.currentGestureIdBits.clear();
3222             mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3223             mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3224             mPointerGesture.currentGestureProperties[0].clear();
3225             mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3226             mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3227             mPointerGesture.currentGestureCoords[0].clear();
3228             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3229                                                                  mPointerGesture.referenceGestureX);
3230             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3231                                                                  mPointerGesture.referenceGestureY);
3232             mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3233         } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3234             // FREEFORM mode.
3235 #if DEBUG_GESTURES
3236             ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3237                   "activeGestureId=%d, currentTouchPointerCount=%d",
3238                   activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3239 #endif
3240             ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3241 
3242             mPointerGesture.currentGestureIdBits.clear();
3243 
3244             BitSet32 mappedTouchIdBits;
3245             BitSet32 usedGestureIdBits;
3246             if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3247                 // Initially, assign the active gesture id to the active touch point
3248                 // if there is one.  No other touch id bits are mapped yet.
3249                 if (!*outCancelPreviousGesture) {
3250                     mappedTouchIdBits.markBit(activeTouchId);
3251                     usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3252                     mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3253                             mPointerGesture.activeGestureId;
3254                 } else {
3255                     mPointerGesture.activeGestureId = -1;
3256                 }
3257             } else {
3258                 // Otherwise, assume we mapped all touches from the previous frame.
3259                 // Reuse all mappings that are still applicable.
3260                 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3261                         mCurrentCookedState.fingerIdBits.value;
3262                 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3263 
3264                 // Check whether we need to choose a new active gesture id because the
3265                 // current went went up.
3266                 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3267                                             ~mCurrentCookedState.fingerIdBits.value);
3268                      !upTouchIdBits.isEmpty();) {
3269                     uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3270                     uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3271                     if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3272                         mPointerGesture.activeGestureId = -1;
3273                         break;
3274                     }
3275                 }
3276             }
3277 
3278 #if DEBUG_GESTURES
3279             ALOGD("Gestures: FREEFORM follow up "
3280                   "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3281                   "activeGestureId=%d",
3282                   mappedTouchIdBits.value, usedGestureIdBits.value,
3283                   mPointerGesture.activeGestureId);
3284 #endif
3285 
3286             BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3287             for (uint32_t i = 0; i < currentFingerCount; i++) {
3288                 uint32_t touchId = idBits.clearFirstMarkedBit();
3289                 uint32_t gestureId;
3290                 if (!mappedTouchIdBits.hasBit(touchId)) {
3291                     gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3292                     mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3293 #if DEBUG_GESTURES
3294                     ALOGD("Gestures: FREEFORM "
3295                           "new mapping for touch id %d -> gesture id %d",
3296                           touchId, gestureId);
3297 #endif
3298                 } else {
3299                     gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3300 #if DEBUG_GESTURES
3301                     ALOGD("Gestures: FREEFORM "
3302                           "existing mapping for touch id %d -> gesture id %d",
3303                           touchId, gestureId);
3304 #endif
3305                 }
3306                 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3307                 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3308 
3309                 const RawPointerData::Pointer& pointer =
3310                         mCurrentRawState.rawPointerData.pointerForId(touchId);
3311                 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3312                 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3313                 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3314 
3315                 mPointerGesture.currentGestureProperties[i].clear();
3316                 mPointerGesture.currentGestureProperties[i].id = gestureId;
3317                 mPointerGesture.currentGestureProperties[i].toolType =
3318                         AMOTION_EVENT_TOOL_TYPE_FINGER;
3319                 mPointerGesture.currentGestureCoords[i].clear();
3320                 mPointerGesture.currentGestureCoords[i]
3321                         .setAxisValue(AMOTION_EVENT_AXIS_X,
3322                                       mPointerGesture.referenceGestureX + deltaX);
3323                 mPointerGesture.currentGestureCoords[i]
3324                         .setAxisValue(AMOTION_EVENT_AXIS_Y,
3325                                       mPointerGesture.referenceGestureY + deltaY);
3326                 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3327                                                                      1.0f);
3328             }
3329 
3330             if (mPointerGesture.activeGestureId < 0) {
3331                 mPointerGesture.activeGestureId =
3332                         mPointerGesture.currentGestureIdBits.firstMarkedBit();
3333 #if DEBUG_GESTURES
3334                 ALOGD("Gestures: FREEFORM new "
3335                       "activeGestureId=%d",
3336                       mPointerGesture.activeGestureId);
3337 #endif
3338             }
3339         }
3340     }
3341 
3342     mPointerController->setButtonState(mCurrentRawState.buttonState);
3343 
3344 #if DEBUG_GESTURES
3345     ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3346           "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3347           "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3348           toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3349           mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3350           mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3351     for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3352         uint32_t id = idBits.clearFirstMarkedBit();
3353         uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3354         const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3355         const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3356         ALOGD("  currentGesture[%d]: index=%d, toolType=%d, "
3357               "x=%0.3f, y=%0.3f, pressure=%0.3f",
3358               id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3359               coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3360               coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3361     }
3362     for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3363         uint32_t id = idBits.clearFirstMarkedBit();
3364         uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3365         const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3366         const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3367         ALOGD("  lastGesture[%d]: index=%d, toolType=%d, "
3368               "x=%0.3f, y=%0.3f, pressure=%0.3f",
3369               id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3370               coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3371               coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3372     }
3373 #endif
3374     return true;
3375 }
3376 
dispatchPointerStylus(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)3377 void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3378     mPointerSimple.currentCoords.clear();
3379     mPointerSimple.currentProperties.clear();
3380 
3381     bool down, hovering;
3382     if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3383         uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3384         uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3385         setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3386                                mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
3387 
3388         hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3389         down = !hovering;
3390 
3391         auto [x, y] = getMouseCursorPosition();
3392         mPointerSimple.currentCoords.copyFrom(
3393                 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3394         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3395         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3396         mPointerSimple.currentProperties.id = 0;
3397         mPointerSimple.currentProperties.toolType =
3398                 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3399     } else {
3400         down = false;
3401         hovering = false;
3402     }
3403 
3404     dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
3405 }
3406 
abortPointerStylus(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)3407 void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3408     abortPointerSimple(when, readTime, policyFlags);
3409 }
3410 
dispatchPointerMouse(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)3411 void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3412     mPointerSimple.currentCoords.clear();
3413     mPointerSimple.currentProperties.clear();
3414 
3415     bool down, hovering;
3416     if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3417         uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3418         uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3419         float deltaX = 0, deltaY = 0;
3420         if (mLastCookedState.mouseIdBits.hasBit(id)) {
3421             uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3422             deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3423                       mLastRawState.rawPointerData.pointers[lastIndex].x) *
3424                     mPointerXMovementScale;
3425             deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3426                       mLastRawState.rawPointerData.pointers[lastIndex].y) *
3427                     mPointerYMovementScale;
3428 
3429             rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3430             mPointerVelocityControl.move(when, &deltaX, &deltaY);
3431 
3432             moveMouseCursor(deltaX, deltaY);
3433         } else {
3434             mPointerVelocityControl.reset();
3435         }
3436 
3437         down = isPointerDown(mCurrentRawState.buttonState);
3438         hovering = !down;
3439 
3440         auto [x, y] = getMouseCursorPosition();
3441         mPointerSimple.currentCoords.copyFrom(
3442                 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3443         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3444         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3445         mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3446                                                   hovering ? 0.0f : 1.0f);
3447         mPointerSimple.currentProperties.id = 0;
3448         mPointerSimple.currentProperties.toolType =
3449                 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3450     } else {
3451         mPointerVelocityControl.reset();
3452 
3453         down = false;
3454         hovering = false;
3455     }
3456 
3457     dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
3458 }
3459 
abortPointerMouse(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)3460 void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3461     abortPointerSimple(when, readTime, policyFlags);
3462 
3463     mPointerVelocityControl.reset();
3464 }
3465 
dispatchPointerSimple(nsecs_t when,nsecs_t readTime,uint32_t policyFlags,bool down,bool hovering)3466 void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3467                                              bool down, bool hovering) {
3468     int32_t metaState = getContext()->getGlobalMetaState();
3469 
3470     if (down || hovering) {
3471         mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
3472         mPointerController->clearSpots();
3473         mPointerController->setButtonState(mCurrentRawState.buttonState);
3474         mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3475     } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
3476         mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3477     }
3478     int32_t displayId = mPointerController->getDisplayId();
3479 
3480     auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
3481 
3482     if (mPointerSimple.down && !down) {
3483         mPointerSimple.down = false;
3484 
3485         // Send up.
3486         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3487                               displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
3488                               mLastRawState.buttonState, MotionClassification::NONE,
3489                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3490                               &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3491                               xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3492                               /* videoFrames */ {});
3493         getListener()->notifyMotion(&args);
3494     }
3495 
3496     if (mPointerSimple.hovering && !hovering) {
3497         mPointerSimple.hovering = false;
3498 
3499         // Send hover exit.
3500         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3501                               displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3502                               metaState, mLastRawState.buttonState, MotionClassification::NONE,
3503                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3504                               &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3505                               xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3506                               /* videoFrames */ {});
3507         getListener()->notifyMotion(&args);
3508     }
3509 
3510     if (down) {
3511         if (!mPointerSimple.down) {
3512             mPointerSimple.down = true;
3513             mPointerSimple.downTime = when;
3514 
3515             // Send down.
3516             NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3517                                   displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3518                                   metaState, mCurrentRawState.buttonState,
3519                                   MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3520                                   &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3521                                   mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3522                                   yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3523             getListener()->notifyMotion(&args);
3524         }
3525 
3526         // Send move.
3527         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3528                               displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
3529                               mCurrentRawState.buttonState, MotionClassification::NONE,
3530                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3531                               &mPointerSimple.currentCoords, mOrientedXPrecision,
3532                               mOrientedYPrecision, xCursorPosition, yCursorPosition,
3533                               mPointerSimple.downTime, /* videoFrames */ {});
3534         getListener()->notifyMotion(&args);
3535     }
3536 
3537     if (hovering) {
3538         if (!mPointerSimple.hovering) {
3539             mPointerSimple.hovering = true;
3540 
3541             // Send hover enter.
3542             NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3543                                   displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3544                                   metaState, mCurrentRawState.buttonState,
3545                                   MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3546                                   &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3547                                   mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3548                                   yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3549             getListener()->notifyMotion(&args);
3550         }
3551 
3552         // Send hover move.
3553         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3554                               displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3555                               metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
3556                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3557                               &mPointerSimple.currentCoords, mOrientedXPrecision,
3558                               mOrientedYPrecision, xCursorPosition, yCursorPosition,
3559                               mPointerSimple.downTime, /* videoFrames */ {});
3560         getListener()->notifyMotion(&args);
3561     }
3562 
3563     if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3564         float vscroll = mCurrentRawState.rawVScroll;
3565         float hscroll = mCurrentRawState.rawHScroll;
3566         mWheelYVelocityControl.move(when, nullptr, &vscroll);
3567         mWheelXVelocityControl.move(when, &hscroll, nullptr);
3568 
3569         // Send scroll.
3570         PointerCoords pointerCoords;
3571         pointerCoords.copyFrom(mPointerSimple.currentCoords);
3572         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3573         pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3574 
3575         NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3576                               displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
3577                               mCurrentRawState.buttonState, MotionClassification::NONE,
3578                               AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3579                               &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3580                               xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3581                               /* videoFrames */ {});
3582         getListener()->notifyMotion(&args);
3583     }
3584 
3585     // Save state.
3586     if (down || hovering) {
3587         mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3588         mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3589     } else {
3590         mPointerSimple.reset();
3591     }
3592 }
3593 
abortPointerSimple(nsecs_t when,nsecs_t readTime,uint32_t policyFlags)3594 void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3595     mPointerSimple.currentCoords.clear();
3596     mPointerSimple.currentProperties.clear();
3597 
3598     dispatchPointerSimple(when, readTime, policyFlags, false, false);
3599 }
3600 
dispatchMotion(nsecs_t when,nsecs_t readTime,uint32_t policyFlags,uint32_t source,int32_t action,int32_t actionButton,int32_t flags,int32_t metaState,int32_t buttonState,int32_t edgeFlags,const PointerProperties * properties,const PointerCoords * coords,const uint32_t * idToIndex,BitSet32 idBits,int32_t changedId,float xPrecision,float yPrecision,nsecs_t downTime)3601 void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3602                                       uint32_t source, int32_t action, int32_t actionButton,
3603                                       int32_t flags, int32_t metaState, int32_t buttonState,
3604                                       int32_t edgeFlags, const PointerProperties* properties,
3605                                       const PointerCoords* coords, const uint32_t* idToIndex,
3606                                       BitSet32 idBits, int32_t changedId, float xPrecision,
3607                                       float yPrecision, nsecs_t downTime) {
3608     PointerCoords pointerCoords[MAX_POINTERS];
3609     PointerProperties pointerProperties[MAX_POINTERS];
3610     uint32_t pointerCount = 0;
3611     while (!idBits.isEmpty()) {
3612         uint32_t id = idBits.clearFirstMarkedBit();
3613         uint32_t index = idToIndex[id];
3614         pointerProperties[pointerCount].copyFrom(properties[index]);
3615         pointerCoords[pointerCount].copyFrom(coords[index]);
3616 
3617         if (changedId >= 0 && id == uint32_t(changedId)) {
3618             action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3619         }
3620 
3621         pointerCount += 1;
3622     }
3623 
3624     ALOG_ASSERT(pointerCount != 0);
3625 
3626     if (changedId >= 0 && pointerCount == 1) {
3627         // Replace initial down and final up action.
3628         // We can compare the action without masking off the changed pointer index
3629         // because we know the index is 0.
3630         if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3631             action = AMOTION_EVENT_ACTION_DOWN;
3632         } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
3633             if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3634                 action = AMOTION_EVENT_ACTION_CANCEL;
3635             } else {
3636                 action = AMOTION_EVENT_ACTION_UP;
3637             }
3638         } else {
3639             // Can't happen.
3640             ALOG_ASSERT(false);
3641         }
3642     }
3643     float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3644     float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3645     if (mDeviceMode == DeviceMode::POINTER) {
3646         auto [x, y] = getMouseCursorPosition();
3647         xCursorPosition = x;
3648         yCursorPosition = y;
3649     }
3650     const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3651     const int32_t deviceId = getDeviceId();
3652     std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
3653     std::for_each(frames.begin(), frames.end(),
3654                   [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
3655     NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3656                           policyFlags, action, actionButton, flags, metaState, buttonState,
3657                           MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3658                           pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3659                           downTime, std::move(frames));
3660     getListener()->notifyMotion(&args);
3661 }
3662 
updateMovedPointers(const PointerProperties * inProperties,const PointerCoords * inCoords,const uint32_t * inIdToIndex,PointerProperties * outProperties,PointerCoords * outCoords,const uint32_t * outIdToIndex,BitSet32 idBits) const3663 bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3664                                            const PointerCoords* inCoords,
3665                                            const uint32_t* inIdToIndex,
3666                                            PointerProperties* outProperties,
3667                                            PointerCoords* outCoords, const uint32_t* outIdToIndex,
3668                                            BitSet32 idBits) const {
3669     bool changed = false;
3670     while (!idBits.isEmpty()) {
3671         uint32_t id = idBits.clearFirstMarkedBit();
3672         uint32_t inIndex = inIdToIndex[id];
3673         uint32_t outIndex = outIdToIndex[id];
3674 
3675         const PointerProperties& curInProperties = inProperties[inIndex];
3676         const PointerCoords& curInCoords = inCoords[inIndex];
3677         PointerProperties& curOutProperties = outProperties[outIndex];
3678         PointerCoords& curOutCoords = outCoords[outIndex];
3679 
3680         if (curInProperties != curOutProperties) {
3681             curOutProperties.copyFrom(curInProperties);
3682             changed = true;
3683         }
3684 
3685         if (curInCoords != curOutCoords) {
3686             curOutCoords.copyFrom(curInCoords);
3687             changed = true;
3688         }
3689     }
3690     return changed;
3691 }
3692 
cancelTouch(nsecs_t when,nsecs_t readTime)3693 void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3694     abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3695     abortTouches(when, readTime, 0 /* policyFlags*/);
3696 }
3697 
3698 // Transform raw coordinate to surface coordinate
rotateAndScale(float & x,float & y)3699 void TouchInputMapper::rotateAndScale(float& x, float& y) {
3700     // Scale to surface coordinate.
3701     const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3702     const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3703 
3704     const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3705     const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3706 
3707     // Rotate to surface coordinate.
3708     // 0 - no swap and reverse.
3709     // 90 - swap x/y and reverse y.
3710     // 180 - reverse x, y.
3711     // 270 - swap x/y and reverse x.
3712     switch (mSurfaceOrientation) {
3713         case DISPLAY_ORIENTATION_0:
3714             x = xScaled + mXTranslate;
3715             y = yScaled + mYTranslate;
3716             break;
3717         case DISPLAY_ORIENTATION_90:
3718             y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3719             x = yScaled + mYTranslate;
3720             break;
3721         case DISPLAY_ORIENTATION_180:
3722             x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3723             y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
3724             break;
3725         case DISPLAY_ORIENTATION_270:
3726             y = xScaled + mXTranslate;
3727             x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
3728             break;
3729         default:
3730             assert(false);
3731     }
3732 }
3733 
isPointInsideSurface(int32_t x,int32_t y)3734 bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
3735     const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3736     const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3737 
3738     return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
3739             xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
3740             y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
3741             yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
3742 }
3743 
findVirtualKeyHit(int32_t x,int32_t y)3744 const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3745     for (const VirtualKey& virtualKey : mVirtualKeys) {
3746 #if DEBUG_VIRTUAL_KEYS
3747         ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3748               "left=%d, top=%d, right=%d, bottom=%d",
3749               x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3750               virtualKey.hitRight, virtualKey.hitBottom);
3751 #endif
3752 
3753         if (virtualKey.isHit(x, y)) {
3754             return &virtualKey;
3755         }
3756     }
3757 
3758     return nullptr;
3759 }
3760 
assignPointerIds(const RawState & last,RawState & current)3761 void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3762     uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3763     uint32_t lastPointerCount = last.rawPointerData.pointerCount;
3764 
3765     current.rawPointerData.clearIdBits();
3766 
3767     if (currentPointerCount == 0) {
3768         // No pointers to assign.
3769         return;
3770     }
3771 
3772     if (lastPointerCount == 0) {
3773         // All pointers are new.
3774         for (uint32_t i = 0; i < currentPointerCount; i++) {
3775             uint32_t id = i;
3776             current.rawPointerData.pointers[i].id = id;
3777             current.rawPointerData.idToIndex[id] = i;
3778             current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
3779         }
3780         return;
3781     }
3782 
3783     if (currentPointerCount == 1 && lastPointerCount == 1 &&
3784         current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
3785         // Only one pointer and no change in count so it must have the same id as before.
3786         uint32_t id = last.rawPointerData.pointers[0].id;
3787         current.rawPointerData.pointers[0].id = id;
3788         current.rawPointerData.idToIndex[id] = 0;
3789         current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
3790         return;
3791     }
3792 
3793     // General case.
3794     // We build a heap of squared euclidean distances between current and last pointers
3795     // associated with the current and last pointer indices.  Then, we find the best
3796     // match (by distance) for each current pointer.
3797     // The pointers must have the same tool type but it is possible for them to
3798     // transition from hovering to touching or vice-versa while retaining the same id.
3799     PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3800 
3801     uint32_t heapSize = 0;
3802     for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3803          currentPointerIndex++) {
3804         for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3805              lastPointerIndex++) {
3806             const RawPointerData::Pointer& currentPointer =
3807                     current.rawPointerData.pointers[currentPointerIndex];
3808             const RawPointerData::Pointer& lastPointer =
3809                     last.rawPointerData.pointers[lastPointerIndex];
3810             if (currentPointer.toolType == lastPointer.toolType) {
3811                 int64_t deltaX = currentPointer.x - lastPointer.x;
3812                 int64_t deltaY = currentPointer.y - lastPointer.y;
3813 
3814                 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3815 
3816                 // Insert new element into the heap (sift up).
3817                 heap[heapSize].currentPointerIndex = currentPointerIndex;
3818                 heap[heapSize].lastPointerIndex = lastPointerIndex;
3819                 heap[heapSize].distance = distance;
3820                 heapSize += 1;
3821             }
3822         }
3823     }
3824 
3825     // Heapify
3826     for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3827         startIndex -= 1;
3828         for (uint32_t parentIndex = startIndex;;) {
3829             uint32_t childIndex = parentIndex * 2 + 1;
3830             if (childIndex >= heapSize) {
3831                 break;
3832             }
3833 
3834             if (childIndex + 1 < heapSize &&
3835                 heap[childIndex + 1].distance < heap[childIndex].distance) {
3836                 childIndex += 1;
3837             }
3838 
3839             if (heap[parentIndex].distance <= heap[childIndex].distance) {
3840                 break;
3841             }
3842 
3843             swap(heap[parentIndex], heap[childIndex]);
3844             parentIndex = childIndex;
3845         }
3846     }
3847 
3848 #if DEBUG_POINTER_ASSIGNMENT
3849     ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3850     for (size_t i = 0; i < heapSize; i++) {
3851         ALOGD("  heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3852               heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3853     }
3854 #endif
3855 
3856     // Pull matches out by increasing order of distance.
3857     // To avoid reassigning pointers that have already been matched, the loop keeps track
3858     // of which last and current pointers have been matched using the matchedXXXBits variables.
3859     // It also tracks the used pointer id bits.
3860     BitSet32 matchedLastBits(0);
3861     BitSet32 matchedCurrentBits(0);
3862     BitSet32 usedIdBits(0);
3863     bool first = true;
3864     for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3865         while (heapSize > 0) {
3866             if (first) {
3867                 // The first time through the loop, we just consume the root element of
3868                 // the heap (the one with smallest distance).
3869                 first = false;
3870             } else {
3871                 // Previous iterations consumed the root element of the heap.
3872                 // Pop root element off of the heap (sift down).
3873                 heap[0] = heap[heapSize];
3874                 for (uint32_t parentIndex = 0;;) {
3875                     uint32_t childIndex = parentIndex * 2 + 1;
3876                     if (childIndex >= heapSize) {
3877                         break;
3878                     }
3879 
3880                     if (childIndex + 1 < heapSize &&
3881                         heap[childIndex + 1].distance < heap[childIndex].distance) {
3882                         childIndex += 1;
3883                     }
3884 
3885                     if (heap[parentIndex].distance <= heap[childIndex].distance) {
3886                         break;
3887                     }
3888 
3889                     swap(heap[parentIndex], heap[childIndex]);
3890                     parentIndex = childIndex;
3891                 }
3892 
3893 #if DEBUG_POINTER_ASSIGNMENT
3894                 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3895                 for (size_t j = 0; j < heapSize; j++) {
3896                     ALOGD("  heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3897                           heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
3898                 }
3899 #endif
3900             }
3901 
3902             heapSize -= 1;
3903 
3904             uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3905             if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3906 
3907             uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3908             if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3909 
3910             matchedCurrentBits.markBit(currentPointerIndex);
3911             matchedLastBits.markBit(lastPointerIndex);
3912 
3913             uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3914             current.rawPointerData.pointers[currentPointerIndex].id = id;
3915             current.rawPointerData.idToIndex[id] = currentPointerIndex;
3916             current.rawPointerData.markIdBit(id,
3917                                              current.rawPointerData.isHovering(
3918                                                      currentPointerIndex));
3919             usedIdBits.markBit(id);
3920 
3921 #if DEBUG_POINTER_ASSIGNMENT
3922             ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3923                   ", distance=%" PRIu64,
3924                   lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3925 #endif
3926             break;
3927         }
3928     }
3929 
3930     // Assign fresh ids to pointers that were not matched in the process.
3931     for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3932         uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3933         uint32_t id = usedIdBits.markFirstUnmarkedBit();
3934 
3935         current.rawPointerData.pointers[currentPointerIndex].id = id;
3936         current.rawPointerData.idToIndex[id] = currentPointerIndex;
3937         current.rawPointerData.markIdBit(id,
3938                                          current.rawPointerData.isHovering(currentPointerIndex));
3939 
3940 #if DEBUG_POINTER_ASSIGNMENT
3941         ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3942 #endif
3943     }
3944 }
3945 
getKeyCodeState(uint32_t sourceMask,int32_t keyCode)3946 int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3947     if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3948         return AKEY_STATE_VIRTUAL;
3949     }
3950 
3951     for (const VirtualKey& virtualKey : mVirtualKeys) {
3952         if (virtualKey.keyCode == keyCode) {
3953             return AKEY_STATE_UP;
3954         }
3955     }
3956 
3957     return AKEY_STATE_UNKNOWN;
3958 }
3959 
getScanCodeState(uint32_t sourceMask,int32_t scanCode)3960 int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3961     if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3962         return AKEY_STATE_VIRTUAL;
3963     }
3964 
3965     for (const VirtualKey& virtualKey : mVirtualKeys) {
3966         if (virtualKey.scanCode == scanCode) {
3967             return AKEY_STATE_UP;
3968         }
3969     }
3970 
3971     return AKEY_STATE_UNKNOWN;
3972 }
3973 
markSupportedKeyCodes(uint32_t sourceMask,size_t numCodes,const int32_t * keyCodes,uint8_t * outFlags)3974 bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3975                                              const int32_t* keyCodes, uint8_t* outFlags) {
3976     for (const VirtualKey& virtualKey : mVirtualKeys) {
3977         for (size_t i = 0; i < numCodes; i++) {
3978             if (virtualKey.keyCode == keyCodes[i]) {
3979                 outFlags[i] = 1;
3980             }
3981         }
3982     }
3983 
3984     return true;
3985 }
3986 
getAssociatedDisplayId()3987 std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3988     if (mParameters.hasAssociatedDisplay) {
3989         if (mDeviceMode == DeviceMode::POINTER) {
3990             return std::make_optional(mPointerController->getDisplayId());
3991         } else {
3992             return std::make_optional(mViewport.displayId);
3993         }
3994     }
3995     return std::nullopt;
3996 }
3997 
moveMouseCursor(float dx,float dy) const3998 void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
3999     if (isPerWindowInputRotationEnabled()) {
4000         // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4001         // space that is oriented with the viewport.
4002         rotateDelta(mViewport.orientation, &dx, &dy);
4003     }
4004 
4005     mPointerController->move(dx, dy);
4006 }
4007 
getMouseCursorPosition() const4008 std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4009     float x = 0;
4010     float y = 0;
4011     mPointerController->getPosition(&x, &y);
4012 
4013     if (!isPerWindowInputRotationEnabled()) return {x, y};
4014     if (!mViewport.isValid()) return {x, y};
4015 
4016     // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4017     // to InputReader's un-rotated coordinate space.
4018     const int32_t orientation = getInverseRotation(mViewport.orientation);
4019     rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4020     return {x, y};
4021 }
4022 
setMouseCursorPosition(float x,float y) const4023 void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4024     if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4025         // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4026         // coordinate space that is oriented with the viewport.
4027         rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4028     }
4029 
4030     mPointerController->setPosition(x, y);
4031 }
4032 
setTouchSpots(const PointerCoords * spotCoords,const uint32_t * spotIdToIndex,BitSet32 spotIdBits,int32_t displayId)4033 void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4034                                      BitSet32 spotIdBits, int32_t displayId) {
4035     std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4036 
4037     for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4038         const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4039         float x = spotCoords[index].getX();
4040         float y = spotCoords[index].getY();
4041         float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4042 
4043         if (isPerWindowInputRotationEnabled()) {
4044             // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4045             // coordinate space.
4046             rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4047         }
4048 
4049         outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4050         outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4051         outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4052     }
4053 
4054     mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4055 }
4056 
4057 } // namespace android
4058