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