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