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