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