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