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