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