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