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