blob: 0733342f3808f708b8226454ec1a6310c7bf3c2c [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wrightaff169e2020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wrightaff169e2020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
23#include "CursorButtonAccumulator.h"
24#include "CursorScrollAccumulator.h"
25#include "TouchButtonAccumulator.h"
26#include "TouchCursorInputMapperCommon.h"
27
28namespace android {
29
30// --- Constants ---
31
32// Maximum amount of latency to add to touch events while waiting for data from an
33// external stylus.
34static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
35
36// Maximum amount of time to wait on touch data before pushing out new pressure data.
37static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
38
39// Artificial latency on synthetic events created from stylus data without corresponding touch
40// data.
41static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
42
43// --- Static Definitions ---
44
45template <typename T>
46inline static void swap(T& a, T& b) {
47 T temp = a;
48 a = b;
49 b = temp;
50}
51
52static float calculateCommonVector(float a, float b) {
53 if (a > 0 && b > 0) {
54 return a < b ? a : b;
55 } else if (a < 0 && b < 0) {
56 return a > b ? a : b;
57 } else {
58 return 0;
59 }
60}
61
62inline static float distance(float x1, float y1, float x2, float y2) {
63 return hypotf(x1 - x2, y1 - y2);
64}
65
66inline static int32_t signExtendNybble(int32_t value) {
67 return value >= 8 ? value - 16 : value;
68}
69
70// --- RawPointerAxes ---
71
72RawPointerAxes::RawPointerAxes() {
73 clear();
74}
75
76void RawPointerAxes::clear() {
77 x.clear();
78 y.clear();
79 pressure.clear();
80 touchMajor.clear();
81 touchMinor.clear();
82 toolMajor.clear();
83 toolMinor.clear();
84 orientation.clear();
85 distance.clear();
86 tiltX.clear();
87 tiltY.clear();
88 trackingId.clear();
89 slot.clear();
90}
91
92// --- RawPointerData ---
93
94RawPointerData::RawPointerData() {
95 clear();
96}
97
98void RawPointerData::clear() {
99 pointerCount = 0;
100 clearIdBits();
101}
102
103void RawPointerData::copyFrom(const RawPointerData& other) {
104 pointerCount = other.pointerCount;
105 hoveringIdBits = other.hoveringIdBits;
106 touchingIdBits = other.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +0800107 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700108
109 for (uint32_t i = 0; i < pointerCount; i++) {
110 pointers[i] = other.pointers[i];
111
112 int id = pointers[i].id;
113 idToIndex[id] = other.idToIndex[id];
114 }
115}
116
117void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
118 float x = 0, y = 0;
119 uint32_t count = touchingIdBits.count();
120 if (count) {
121 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
122 uint32_t id = idBits.clearFirstMarkedBit();
123 const Pointer& pointer = pointerForId(id);
124 x += pointer.x;
125 y += pointer.y;
126 }
127 x /= count;
128 y /= count;
129 }
130 *outX = x;
131 *outY = y;
132}
133
134// --- CookedPointerData ---
135
136CookedPointerData::CookedPointerData() {
137 clear();
138}
139
140void CookedPointerData::clear() {
141 pointerCount = 0;
142 hoveringIdBits.clear();
143 touchingIdBits.clear();
arthurhung65600042020-04-30 17:55:40 +0800144 canceledIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700145}
146
147void CookedPointerData::copyFrom(const CookedPointerData& other) {
148 pointerCount = other.pointerCount;
149 hoveringIdBits = other.hoveringIdBits;
150 touchingIdBits = other.touchingIdBits;
151
152 for (uint32_t i = 0; i < pointerCount; i++) {
153 pointerProperties[i].copyFrom(other.pointerProperties[i]);
154 pointerCoords[i].copyFrom(other.pointerCoords[i]);
155
156 int id = pointerProperties[i].id;
157 idToIndex[id] = other.idToIndex[id];
158 }
159}
160
161// --- TouchInputMapper ---
162
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800163TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
164 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700165 mSource(0),
Michael Wrightaff169e2020-07-02 18:30:52 +0100166 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800167 mRawSurfaceWidth(-1),
168 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700169 mSurfaceLeft(0),
170 mSurfaceTop(0),
171 mPhysicalWidth(-1),
172 mPhysicalHeight(-1),
173 mPhysicalLeft(0),
174 mPhysicalTop(0),
175 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
176
177TouchInputMapper::~TouchInputMapper() {}
178
179uint32_t TouchInputMapper::getSources() {
180 return mSource;
181}
182
183void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
184 InputMapper::populateDeviceInfo(info);
185
Michael Wrightaff169e2020-07-02 18:30:52 +0100186 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700187 info->addMotionRange(mOrientedRanges.x);
188 info->addMotionRange(mOrientedRanges.y);
189 info->addMotionRange(mOrientedRanges.pressure);
190
191 if (mOrientedRanges.haveSize) {
192 info->addMotionRange(mOrientedRanges.size);
193 }
194
195 if (mOrientedRanges.haveTouchSize) {
196 info->addMotionRange(mOrientedRanges.touchMajor);
197 info->addMotionRange(mOrientedRanges.touchMinor);
198 }
199
200 if (mOrientedRanges.haveToolSize) {
201 info->addMotionRange(mOrientedRanges.toolMajor);
202 info->addMotionRange(mOrientedRanges.toolMinor);
203 }
204
205 if (mOrientedRanges.haveOrientation) {
206 info->addMotionRange(mOrientedRanges.orientation);
207 }
208
209 if (mOrientedRanges.haveDistance) {
210 info->addMotionRange(mOrientedRanges.distance);
211 }
212
213 if (mOrientedRanges.haveTilt) {
214 info->addMotionRange(mOrientedRanges.tilt);
215 }
216
217 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
218 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
219 0.0f);
220 }
221 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
222 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
223 0.0f);
224 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100225 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700226 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
227 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
228 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
229 x.fuzz, x.resolution);
230 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
231 y.fuzz, y.resolution);
232 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
233 x.fuzz, x.resolution);
234 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
235 y.fuzz, y.resolution);
236 }
237 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
238 }
239}
240
241void TouchInputMapper::dump(std::string& dump) {
242 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
243 dumpParameters(dump);
244 dumpVirtualKeys(dump);
245 dumpRawPointerAxes(dump);
246 dumpCalibration(dump);
247 dumpAffineTransformation(dump);
248 dumpSurface(dump);
249
250 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
251 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
252 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
253 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
254 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
255 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
256 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
257 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
258 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
259 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
260 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
261 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
262 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
263 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
264 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
265 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
266 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
267
268 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
269 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
270 mLastRawState.rawPointerData.pointerCount);
271 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
272 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
273 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
274 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
275 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
276 "toolType=%d, isHovering=%s\n",
277 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
278 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
279 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
280 pointer.distance, pointer.toolType, toString(pointer.isHovering));
281 }
282
283 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
284 mLastCookedState.buttonState);
285 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
286 mLastCookedState.cookedPointerData.pointerCount);
287 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
288 const PointerProperties& pointerProperties =
289 mLastCookedState.cookedPointerData.pointerProperties[i];
290 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
291 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
292 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, "
293 "toolMinor=%0.3f, "
294 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
295 "toolType=%d, isHovering=%s\n",
296 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
297 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
298 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
299 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
300 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
301 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
302 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
303 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
304 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
305 pointerProperties.toolType,
306 toString(mLastCookedState.cookedPointerData.isHovering(i)));
307 }
308
309 dump += INDENT3 "Stylus Fusion:\n";
310 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
311 toString(mExternalStylusConnected));
312 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
313 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
314 mExternalStylusFusionTimeout);
315 dump += INDENT3 "External Stylus State:\n";
316 dumpStylusState(dump, mExternalStylusState);
317
Michael Wrightaff169e2020-07-02 18:30:52 +0100318 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700319 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
320 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
321 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
322 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
323 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
324 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
325 }
326}
327
328const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
329 switch (deviceMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100330 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 return "disabled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100332 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 return "direct";
Michael Wrightaff169e2020-07-02 18:30:52 +0100334 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 return "unscaled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100336 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 return "navigation";
Michael Wrightaff169e2020-07-02 18:30:52 +0100338 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 return "pointer";
340 }
341 return "unknown";
342}
343
344void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
345 uint32_t changes) {
346 InputMapper::configure(when, config, changes);
347
348 mConfig = *config;
349
350 if (!changes) { // first time only
351 // Configure basic parameters.
352 configureParameters();
353
354 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 mCursorScrollAccumulator.configure(getDeviceContext());
356 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357
358 // Configure absolute axis information.
359 configureRawPointerAxes();
360
361 // Prepare input device calibration.
362 parseCalibration();
363 resolveCalibration();
364 }
365
366 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
367 // Update location calibration to reflect current settings
368 updateAffineTransformation();
369 }
370
371 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
372 // Update pointer speed.
373 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
374 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
375 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
376 }
377
378 bool resetNeeded = false;
379 if (!changes ||
380 (changes &
381 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800382 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383 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.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800394 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800395 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700396 }
397}
398
399void TouchInputMapper::resolveExternalStylusPresence() {
400 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800401 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 mExternalStylusConnected = !devices.empty();
403
404 if (!mExternalStylusConnected) {
405 resetExternalStylus();
406 }
407}
408
409void TouchInputMapper::configureParameters() {
410 // Use the pointer presentation mode for devices that do not support distinct
411 // multitouch. The spot-based presentation relies on being able to accurately
412 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800413 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wrightaff169e2020-07-02 18:30:52 +0100414 ? Parameters::GestureMode::SINGLE_TOUCH
415 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700416
417 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
419 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 if (gestureModeString == "single-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100421 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422 } else if (gestureModeString == "multi-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100423 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700424 } else if (gestureModeString != "default") {
425 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
426 }
427 }
428
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 // The device is a touch screen.
Michael Wrightaff169e2020-07-02 18:30:52 +0100431 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800432 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700433 // The device is a pointing device like a track pad.
Michael Wrightaff169e2020-07-02 18:30:52 +0100434 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
436 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437 // The device is a cursor device with a touch pad attached.
438 // By default don't use the touch pad to move the pointer.
Michael Wrightaff169e2020-07-02 18:30:52 +0100439 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 } else {
441 // The device is a touch pad of unknown purpose.
Michael Wrightaff169e2020-07-02 18:30:52 +0100442 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 }
444
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800445 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446
447 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800448 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
449 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 if (deviceTypeString == "touchScreen") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100451 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452 } else if (deviceTypeString == "touchPad") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100453 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 } else if (deviceTypeString == "touchNavigation") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100455 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 } else if (deviceTypeString == "pointer") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString != "default") {
459 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
460 }
461 }
462
Michael Wrightaff169e2020-07-02 18:30:52 +0100463 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800464 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
465 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700466
467 mParameters.hasAssociatedDisplay = false;
468 mParameters.associatedDisplayIsExternal = false;
469 if (mParameters.orientationAware ||
Michael Wrightaff169e2020-07-02 18:30:52 +0100470 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
471 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472 mParameters.hasAssociatedDisplay = true;
Michael Wrightaff169e2020-07-02 18:30:52 +0100473 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800474 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800476 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
477 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
479 }
480 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800481 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482 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.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800488 mParameters.wake = getDeviceContext().isExternal();
489 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490}
491
492void TouchInputMapper::dumpParameters(std::string& dump) {
493 dump += INDENT3 "Parameters:\n";
494
495 switch (mParameters.gestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100496 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700497 dump += INDENT4 "GestureMode: single-touch\n";
498 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100499 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500 dump += INDENT4 "GestureMode: multi-touch\n";
501 break;
502 default:
503 assert(false);
504 }
505
506 switch (mParameters.deviceType) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100507 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508 dump += INDENT4 "DeviceType: touchScreen\n";
509 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100510 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700511 dump += INDENT4 "DeviceType: touchPad\n";
512 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100513 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514 dump += INDENT4 "DeviceType: touchNavigation\n";
515 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100516 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700517 dump += INDENT4 "DeviceType: pointer\n";
518 break;
519 default:
520 ALOG_ASSERT(false);
521 }
522
523 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
524 "displayId='%s'\n",
525 toString(mParameters.hasAssociatedDisplay),
526 toString(mParameters.associatedDisplayIsExternal),
527 mParameters.uniqueDisplayId.c_str());
528 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
529}
530
531void TouchInputMapper::configureRawPointerAxes() {
532 mRawPointerAxes.clear();
533}
534
535void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
536 dump += INDENT3 "Raw Touch Axes:\n";
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
550}
551
552bool TouchInputMapper::hasExternalStylus() const {
553 return mExternalStylusConnected;
554}
555
556/**
557 * Determine which DisplayViewport to use.
558 * 1. If display port is specified, return the matching viewport. If matching viewport not
559 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800560 * 2. Always use the suggested viewport from WindowManagerService for pointers.
561 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700562 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800563 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 */
565std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800566 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800567 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 if (displayPort) {
569 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800570 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700571 }
572
Michael Wrightaff169e2020-07-02 18:30:52 +0100573 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800574 std::optional<DisplayViewport> viewport =
575 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
576 if (viewport) {
577 return viewport;
578 } else {
579 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
580 mConfig.defaultPointerDisplayId);
581 }
582 }
583
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700584 // Check if uniqueDisplayId is specified in idc file.
585 if (!mParameters.uniqueDisplayId.empty()) {
586 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
587 }
588
589 ViewportType viewportTypeToUse;
590 if (mParameters.associatedDisplayIsExternal) {
591 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
592 } else {
593 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
594 }
595
596 std::optional<DisplayViewport> viewport =
597 mConfig.getDisplayViewportByType(viewportTypeToUse);
598 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
599 ALOGW("Input device %s should be associated with external display, "
600 "fallback to internal one for the external viewport is not found.",
601 getDeviceName().c_str());
602 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
603 }
604
605 return viewport;
606 }
607
608 // No associated display, return a non-display viewport.
609 DisplayViewport newViewport;
610 // Raw width and height in the natural orientation.
611 int32_t rawWidth = mRawPointerAxes.getRawWidth();
612 int32_t rawHeight = mRawPointerAxes.getRawHeight();
613 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
614 return std::make_optional(newViewport);
615}
616
617void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100618 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700619
620 resolveExternalStylusPresence();
621
622 // Determine device mode.
Michael Wrightaff169e2020-07-02 18:30:52 +0100623 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800624 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625 mSource = AINPUT_SOURCE_MOUSE;
Michael Wrightaff169e2020-07-02 18:30:52 +0100626 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700627 if (hasStylus()) {
628 mSource |= AINPUT_SOURCE_STYLUS;
629 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100630 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 mParameters.hasAssociatedDisplay) {
632 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wrightaff169e2020-07-02 18:30:52 +0100633 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700634 if (hasStylus()) {
635 mSource |= AINPUT_SOURCE_STYLUS;
636 }
637 if (hasExternalStylus()) {
638 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
639 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100640 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700641 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wrightaff169e2020-07-02 18:30:52 +0100642 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700643 } else {
644 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wrightaff169e2020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 }
647
648 // Ensure we have valid X and Y axes.
649 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
650 ALOGW("Touch device '%s' did not report support for X or Y axis! "
651 "The device will be inoperable.",
652 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100653 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700654 return;
655 }
656
657 // Get associated display dimensions.
658 std::optional<DisplayViewport> newViewport = findViewport();
659 if (!newViewport) {
660 ALOGI("Touch device '%s' could not query the properties of its associated "
661 "display. The device will be inoperable until the display size "
662 "becomes available.",
663 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100664 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 return;
666 }
667
668 // Raw width and height in the natural orientation.
669 int32_t rawWidth = mRawPointerAxes.getRawWidth();
670 int32_t rawHeight = mRawPointerAxes.getRawHeight();
671
672 bool viewportChanged = mViewport != *newViewport;
673 if (viewportChanged) {
674 mViewport = *newViewport;
675
Michael Wrightaff169e2020-07-02 18:30:52 +0100676 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700677 // Convert rotated viewport to natural surface coordinates.
678 int32_t naturalLogicalWidth, naturalLogicalHeight;
679 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
680 int32_t naturalPhysicalLeft, naturalPhysicalTop;
681 int32_t naturalDeviceWidth, naturalDeviceHeight;
682 switch (mViewport.orientation) {
683 case DISPLAY_ORIENTATION_90:
684 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
685 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
686 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
687 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800688 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700689 naturalPhysicalTop = mViewport.physicalLeft;
690 naturalDeviceWidth = mViewport.deviceHeight;
691 naturalDeviceHeight = mViewport.deviceWidth;
692 break;
693 case DISPLAY_ORIENTATION_180:
694 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
695 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
696 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
697 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
698 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
699 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
700 naturalDeviceWidth = mViewport.deviceWidth;
701 naturalDeviceHeight = mViewport.deviceHeight;
702 break;
703 case DISPLAY_ORIENTATION_270:
704 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
705 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
706 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
707 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
708 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800709 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700710 naturalDeviceWidth = mViewport.deviceHeight;
711 naturalDeviceHeight = mViewport.deviceWidth;
712 break;
713 case DISPLAY_ORIENTATION_0:
714 default:
715 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
716 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
717 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
718 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
719 naturalPhysicalLeft = mViewport.physicalLeft;
720 naturalPhysicalTop = mViewport.physicalTop;
721 naturalDeviceWidth = mViewport.deviceWidth;
722 naturalDeviceHeight = mViewport.deviceHeight;
723 break;
724 }
725
726 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
727 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
728 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
729 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
730 }
731
732 mPhysicalWidth = naturalPhysicalWidth;
733 mPhysicalHeight = naturalPhysicalHeight;
734 mPhysicalLeft = naturalPhysicalLeft;
735 mPhysicalTop = naturalPhysicalTop;
736
Arthur Hung4197f6b2020-03-16 15:39:59 +0800737 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
738 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700739 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
740 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800741 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
742 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700743
744 mSurfaceOrientation =
745 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
746 } else {
747 mPhysicalWidth = rawWidth;
748 mPhysicalHeight = rawHeight;
749 mPhysicalLeft = 0;
750 mPhysicalTop = 0;
751
Arthur Hung4197f6b2020-03-16 15:39:59 +0800752 mRawSurfaceWidth = rawWidth;
753 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700754 mSurfaceLeft = 0;
755 mSurfaceTop = 0;
756 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
757 }
758 }
759
760 // If moving between pointer modes, need to reset some state.
761 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
762 if (deviceModeChanged) {
763 mOrientedRanges.clear();
764 }
765
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800766 // Create pointer controller if needed.
Michael Wrightaff169e2020-07-02 18:30:52 +0100767 if (mDeviceMode == DeviceMode::POINTER ||
768 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800769 if (mPointerController == nullptr) {
770 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700771 }
772 } else {
Michael Wright7a376672020-06-26 20:51:44 +0100773 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700774 }
775
776 if (viewportChanged || deviceModeChanged) {
777 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
778 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800779 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700780 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
781
782 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800783 mXScale = float(mRawSurfaceWidth) / rawWidth;
784 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700785 mXTranslate = -mSurfaceLeft;
786 mYTranslate = -mSurfaceTop;
787 mXPrecision = 1.0f / mXScale;
788 mYPrecision = 1.0f / mYScale;
789
790 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
791 mOrientedRanges.x.source = mSource;
792 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
793 mOrientedRanges.y.source = mSource;
794
795 configureVirtualKeys();
796
797 // Scale factor for terms that are not oriented in a particular axis.
798 // If the pixels are square then xScale == yScale otherwise we fake it
799 // by choosing an average.
800 mGeometricScale = avg(mXScale, mYScale);
801
802 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800803 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700804
805 // Size factors.
Michael Wrightaff169e2020-07-02 18:30:52 +0100806 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700807 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
808 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
809 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
810 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
811 } else {
812 mSizeScale = 0.0f;
813 }
814
815 mOrientedRanges.haveTouchSize = true;
816 mOrientedRanges.haveToolSize = true;
817 mOrientedRanges.haveSize = true;
818
819 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
820 mOrientedRanges.touchMajor.source = mSource;
821 mOrientedRanges.touchMajor.min = 0;
822 mOrientedRanges.touchMajor.max = diagonalSize;
823 mOrientedRanges.touchMajor.flat = 0;
824 mOrientedRanges.touchMajor.fuzz = 0;
825 mOrientedRanges.touchMajor.resolution = 0;
826
827 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
828 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
829
830 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
831 mOrientedRanges.toolMajor.source = mSource;
832 mOrientedRanges.toolMajor.min = 0;
833 mOrientedRanges.toolMajor.max = diagonalSize;
834 mOrientedRanges.toolMajor.flat = 0;
835 mOrientedRanges.toolMajor.fuzz = 0;
836 mOrientedRanges.toolMajor.resolution = 0;
837
838 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
839 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
840
841 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
842 mOrientedRanges.size.source = mSource;
843 mOrientedRanges.size.min = 0;
844 mOrientedRanges.size.max = 1.0;
845 mOrientedRanges.size.flat = 0;
846 mOrientedRanges.size.fuzz = 0;
847 mOrientedRanges.size.resolution = 0;
848 } else {
849 mSizeScale = 0.0f;
850 }
851
852 // Pressure factors.
853 mPressureScale = 0;
854 float pressureMax = 1.0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100855 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
856 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700857 if (mCalibration.havePressureScale) {
858 mPressureScale = mCalibration.pressureScale;
859 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
860 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
861 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
862 }
863 }
864
865 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
866 mOrientedRanges.pressure.source = mSource;
867 mOrientedRanges.pressure.min = 0;
868 mOrientedRanges.pressure.max = pressureMax;
869 mOrientedRanges.pressure.flat = 0;
870 mOrientedRanges.pressure.fuzz = 0;
871 mOrientedRanges.pressure.resolution = 0;
872
873 // Tilt
874 mTiltXCenter = 0;
875 mTiltXScale = 0;
876 mTiltYCenter = 0;
877 mTiltYScale = 0;
878 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
879 if (mHaveTilt) {
880 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
881 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
882 mTiltXScale = M_PI / 180;
883 mTiltYScale = M_PI / 180;
884
885 mOrientedRanges.haveTilt = true;
886
887 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
888 mOrientedRanges.tilt.source = mSource;
889 mOrientedRanges.tilt.min = 0;
890 mOrientedRanges.tilt.max = M_PI_2;
891 mOrientedRanges.tilt.flat = 0;
892 mOrientedRanges.tilt.fuzz = 0;
893 mOrientedRanges.tilt.resolution = 0;
894 }
895
896 // Orientation
897 mOrientationScale = 0;
898 if (mHaveTilt) {
899 mOrientedRanges.haveOrientation = true;
900
901 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
902 mOrientedRanges.orientation.source = mSource;
903 mOrientedRanges.orientation.min = -M_PI;
904 mOrientedRanges.orientation.max = M_PI;
905 mOrientedRanges.orientation.flat = 0;
906 mOrientedRanges.orientation.fuzz = 0;
907 mOrientedRanges.orientation.resolution = 0;
908 } else if (mCalibration.orientationCalibration !=
Michael Wrightaff169e2020-07-02 18:30:52 +0100909 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 if (mCalibration.orientationCalibration ==
Michael Wrightaff169e2020-07-02 18:30:52 +0100911 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 if (mRawPointerAxes.orientation.valid) {
913 if (mRawPointerAxes.orientation.maxValue > 0) {
914 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
915 } else if (mRawPointerAxes.orientation.minValue < 0) {
916 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
917 } else {
918 mOrientationScale = 0;
919 }
920 }
921 }
922
923 mOrientedRanges.haveOrientation = true;
924
925 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
926 mOrientedRanges.orientation.source = mSource;
927 mOrientedRanges.orientation.min = -M_PI_2;
928 mOrientedRanges.orientation.max = M_PI_2;
929 mOrientedRanges.orientation.flat = 0;
930 mOrientedRanges.orientation.fuzz = 0;
931 mOrientedRanges.orientation.resolution = 0;
932 }
933
934 // Distance
935 mDistanceScale = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100936 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
937 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700938 if (mCalibration.haveDistanceScale) {
939 mDistanceScale = mCalibration.distanceScale;
940 } else {
941 mDistanceScale = 1.0f;
942 }
943 }
944
945 mOrientedRanges.haveDistance = true;
946
947 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
948 mOrientedRanges.distance.source = mSource;
949 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
950 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
951 mOrientedRanges.distance.flat = 0;
952 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
953 mOrientedRanges.distance.resolution = 0;
954 }
955
956 // Compute oriented precision, scales and ranges.
957 // Note that the maximum value reported is an inclusive maximum value so it is one
958 // unit less than the total width or height of surface.
959 switch (mSurfaceOrientation) {
960 case DISPLAY_ORIENTATION_90:
961 case DISPLAY_ORIENTATION_270:
962 mOrientedXPrecision = mYPrecision;
963 mOrientedYPrecision = mXPrecision;
964
965 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800966 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 mOrientedRanges.x.flat = 0;
968 mOrientedRanges.x.fuzz = 0;
969 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
970
971 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800972 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 mOrientedRanges.y.flat = 0;
974 mOrientedRanges.y.fuzz = 0;
975 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
976 break;
977
978 default:
979 mOrientedXPrecision = mXPrecision;
980 mOrientedYPrecision = mYPrecision;
981
982 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800983 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700984 mOrientedRanges.x.flat = 0;
985 mOrientedRanges.x.fuzz = 0;
986 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
987
988 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 mOrientedRanges.y.flat = 0;
991 mOrientedRanges.y.fuzz = 0;
992 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
993 break;
994 }
995
996 // Location
997 updateAffineTransformation();
998
Michael Wrightaff169e2020-07-02 18:30:52 +0100999 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 // Compute pointer gesture detection parameters.
1001 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001002 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003
1004 // Scale movements such that one whole swipe of the touch pad covers a
1005 // given area relative to the diagonal size of the display when no acceleration
1006 // is applied.
1007 // Assume that the touch pad has a square aspect ratio such that movements in
1008 // X and Y of the same number of raw units cover the same physical distance.
1009 mPointerXMovementScale =
1010 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1011 mPointerYMovementScale = mPointerXMovementScale;
1012
1013 // Scale zooms to cover a smaller range of the display than movements do.
1014 // This value determines the area around the pointer that is affected by freeform
1015 // pointer gestures.
1016 mPointerXZoomScale =
1017 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1018 mPointerYZoomScale = mPointerXZoomScale;
1019
1020 // Max width between pointers to detect a swipe gesture is more than some fraction
1021 // of the diagonal axis of the touch pad. Touches that are wider than this are
1022 // translated into freeform gestures.
1023 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1024
1025 // Abort current pointer usages because the state has changed.
1026 abortPointerUsage(when, 0 /*policyFlags*/);
1027 }
1028
1029 // Inform the dispatcher about the changes.
1030 *outResetNeeded = true;
1031 bumpGeneration();
1032 }
1033}
1034
1035void TouchInputMapper::dumpSurface(std::string& dump) {
1036 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001037 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1038 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1040 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001041 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1042 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1044 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1045 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1046 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1047 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1048}
1049
1050void TouchInputMapper::configureVirtualKeys() {
1051 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001052 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053
1054 mVirtualKeys.clear();
1055
1056 if (virtualKeyDefinitions.size() == 0) {
1057 return;
1058 }
1059
1060 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1061 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1062 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1063 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1064
1065 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1066 VirtualKey virtualKey;
1067
1068 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1069 int32_t keyCode;
1070 int32_t dummyKeyMetaState;
1071 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001072 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1073 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001074 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1075 continue; // drop the key
1076 }
1077
1078 virtualKey.keyCode = keyCode;
1079 virtualKey.flags = flags;
1080
1081 // convert the key definition's display coordinates into touch coordinates for a hit box
1082 int32_t halfWidth = virtualKeyDefinition.width / 2;
1083 int32_t halfHeight = virtualKeyDefinition.height / 2;
1084
1085 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001086 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001087 touchScreenLeft;
1088 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001089 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001091 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1092 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001094 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1095 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096 touchScreenTop;
1097 mVirtualKeys.push_back(virtualKey);
1098 }
1099}
1100
1101void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1102 if (!mVirtualKeys.empty()) {
1103 dump += INDENT3 "Virtual Keys:\n";
1104
1105 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1106 const VirtualKey& virtualKey = mVirtualKeys[i];
1107 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1108 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1109 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1110 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1111 }
1112 }
1113}
1114
1115void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001116 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 Calibration& out = mCalibration;
1118
1119 // Size
Michael Wrightaff169e2020-07-02 18:30:52 +01001120 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 String8 sizeCalibrationString;
1122 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1123 if (sizeCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001124 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 } else if (sizeCalibrationString == "geometric") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001126 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 } else if (sizeCalibrationString == "diameter") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001128 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 } else if (sizeCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 } else if (sizeCalibrationString == "area") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001132 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 } else if (sizeCalibrationString != "default") {
1134 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1135 }
1136 }
1137
1138 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1139 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1140 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1141
1142 // Pressure
Michael Wrightaff169e2020-07-02 18:30:52 +01001143 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 String8 pressureCalibrationString;
1145 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1146 if (pressureCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001147 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (pressureCalibrationString == "physical") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001149 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 } else if (pressureCalibrationString == "amplitude") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001151 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001152 } else if (pressureCalibrationString != "default") {
1153 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1154 pressureCalibrationString.string());
1155 }
1156 }
1157
1158 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1159
1160 // Orientation
Michael Wrightaff169e2020-07-02 18:30:52 +01001161 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 String8 orientationCalibrationString;
1163 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1164 if (orientationCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001165 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (orientationCalibrationString == "interpolated") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001167 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (orientationCalibrationString == "vector") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001169 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (orientationCalibrationString != "default") {
1171 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1172 orientationCalibrationString.string());
1173 }
1174 }
1175
1176 // Distance
Michael Wrightaff169e2020-07-02 18:30:52 +01001177 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 String8 distanceCalibrationString;
1179 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1180 if (distanceCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001181 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (distanceCalibrationString == "scaled") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001183 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (distanceCalibrationString != "default") {
1185 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1186 distanceCalibrationString.string());
1187 }
1188 }
1189
1190 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1191
Michael Wrightaff169e2020-07-02 18:30:52 +01001192 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 String8 coverageCalibrationString;
1194 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1195 if (coverageCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001196 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (coverageCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001198 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (coverageCalibrationString != "default") {
1200 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1201 coverageCalibrationString.string());
1202 }
1203 }
1204}
1205
1206void TouchInputMapper::resolveCalibration() {
1207 // Size
1208 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001209 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1210 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 }
1212 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001213 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215
1216 // Pressure
1217 if (mRawPointerAxes.pressure.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001218 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1219 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 }
1221 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001222 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 }
1224
1225 // Orientation
1226 if (mRawPointerAxes.orientation.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001227 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1228 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001231 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233
1234 // Distance
1235 if (mRawPointerAxes.distance.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001236 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1237 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001240 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242
1243 // Coverage
Michael Wrightaff169e2020-07-02 18:30:52 +01001244 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1245 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247}
1248
1249void TouchInputMapper::dumpCalibration(std::string& dump) {
1250 dump += INDENT3 "Calibration:\n";
1251
1252 // Size
1253 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001254 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 dump += INDENT4 "touch.size.calibration: none\n";
1256 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001257 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 dump += INDENT4 "touch.size.calibration: geometric\n";
1259 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001260 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 dump += INDENT4 "touch.size.calibration: diameter\n";
1262 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001263 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 dump += INDENT4 "touch.size.calibration: box\n";
1265 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001266 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 dump += INDENT4 "touch.size.calibration: area\n";
1268 break;
1269 default:
1270 ALOG_ASSERT(false);
1271 }
1272
1273 if (mCalibration.haveSizeScale) {
1274 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1275 }
1276
1277 if (mCalibration.haveSizeBias) {
1278 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1279 }
1280
1281 if (mCalibration.haveSizeIsSummed) {
1282 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1283 toString(mCalibration.sizeIsSummed));
1284 }
1285
1286 // Pressure
1287 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001288 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 dump += INDENT4 "touch.pressure.calibration: none\n";
1290 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001291 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 dump += INDENT4 "touch.pressure.calibration: physical\n";
1293 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001294 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1296 break;
1297 default:
1298 ALOG_ASSERT(false);
1299 }
1300
1301 if (mCalibration.havePressureScale) {
1302 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1303 }
1304
1305 // Orientation
1306 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001307 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.orientation.calibration: none\n";
1309 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001310 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1312 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001313 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.orientation.calibration: vector\n";
1315 break;
1316 default:
1317 ALOG_ASSERT(false);
1318 }
1319
1320 // Distance
1321 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001322 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001323 dump += INDENT4 "touch.distance.calibration: none\n";
1324 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001325 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.distance.calibration: scaled\n";
1327 break;
1328 default:
1329 ALOG_ASSERT(false);
1330 }
1331
1332 if (mCalibration.haveDistanceScale) {
1333 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1334 }
1335
1336 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001337 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.coverage.calibration: none\n";
1339 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001340 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.coverage.calibration: box\n";
1342 break;
1343 default:
1344 ALOG_ASSERT(false);
1345 }
1346}
1347
1348void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1349 dump += INDENT3 "Affine Transformation:\n";
1350
1351 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1352 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1353 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1354 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1355 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1356 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1357}
1358
1359void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001360 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 mSurfaceOrientation);
1362}
1363
1364void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001365 mCursorButtonAccumulator.reset(getDeviceContext());
1366 mCursorScrollAccumulator.reset(getDeviceContext());
1367 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368
1369 mPointerVelocityControl.reset();
1370 mWheelXVelocityControl.reset();
1371 mWheelYVelocityControl.reset();
1372
1373 mRawStatesPending.clear();
1374 mCurrentRawState.clear();
1375 mCurrentCookedState.clear();
1376 mLastRawState.clear();
1377 mLastCookedState.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001378 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 mSentHoverEnter = false;
1380 mHavePointerIds = false;
1381 mCurrentMotionAborted = false;
1382 mDownTime = 0;
1383
1384 mCurrentVirtualKey.down = false;
1385
1386 mPointerGesture.reset();
1387 mPointerSimple.reset();
1388 resetExternalStylus();
1389
1390 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001391 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001392 mPointerController->clearSpots();
1393 }
1394
1395 InputMapper::reset(when);
1396}
1397
1398void TouchInputMapper::resetExternalStylus() {
1399 mExternalStylusState.clear();
1400 mExternalStylusId = -1;
1401 mExternalStylusFusionTimeout = LLONG_MAX;
1402 mExternalStylusDataPending = false;
1403}
1404
1405void TouchInputMapper::clearStylusDataPendingFlags() {
1406 mExternalStylusDataPending = false;
1407 mExternalStylusFusionTimeout = LLONG_MAX;
1408}
1409
1410void TouchInputMapper::process(const RawEvent* rawEvent) {
1411 mCursorButtonAccumulator.process(rawEvent);
1412 mCursorScrollAccumulator.process(rawEvent);
1413 mTouchButtonAccumulator.process(rawEvent);
1414
1415 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1416 sync(rawEvent->when);
1417 }
1418}
1419
1420void TouchInputMapper::sync(nsecs_t when) {
1421 const RawState* last =
1422 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1423
1424 // Push a new state.
1425 mRawStatesPending.emplace_back();
1426
1427 RawState* next = &mRawStatesPending.back();
1428 next->clear();
1429 next->when = when;
1430
1431 // Sync button state.
1432 next->buttonState =
1433 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1434
1435 // Sync scroll
1436 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1437 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1438 mCursorScrollAccumulator.finishSync();
1439
1440 // Sync touch
1441 syncTouch(when, next);
1442
1443 // Assign pointer ids.
1444 if (!mHavePointerIds) {
1445 assignPointerIds(last, next);
1446 }
1447
1448#if DEBUG_RAW_EVENTS
1449 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhung65600042020-04-30 17:55:40 +08001450 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1452 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhung65600042020-04-30 17:55:40 +08001453 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1454 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455#endif
1456
1457 processRawTouches(false /*timeout*/);
1458}
1459
1460void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001461 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462 // Drop all input if the device is disabled.
1463 mCurrentRawState.clear();
1464 mRawStatesPending.clear();
1465 return;
1466 }
1467
1468 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1469 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1470 // touching the current state will only observe the events that have been dispatched to the
1471 // rest of the pipeline.
1472 const size_t N = mRawStatesPending.size();
1473 size_t count;
1474 for (count = 0; count < N; count++) {
1475 const RawState& next = mRawStatesPending[count];
1476
1477 // A failure to assign the stylus id means that we're waiting on stylus data
1478 // and so should defer the rest of the pipeline.
1479 if (assignExternalStylusId(next, timeout)) {
1480 break;
1481 }
1482
1483 // All ready to go.
1484 clearStylusDataPendingFlags();
1485 mCurrentRawState.copyFrom(next);
1486 if (mCurrentRawState.when < mLastRawState.when) {
1487 mCurrentRawState.when = mLastRawState.when;
1488 }
1489 cookAndDispatch(mCurrentRawState.when);
1490 }
1491 if (count != 0) {
1492 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1493 }
1494
1495 if (mExternalStylusDataPending) {
1496 if (timeout) {
1497 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1498 clearStylusDataPendingFlags();
1499 mCurrentRawState.copyFrom(mLastRawState);
1500#if DEBUG_STYLUS_FUSION
1501 ALOGD("Timeout expired, synthesizing event with new stylus data");
1502#endif
1503 cookAndDispatch(when);
1504 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1505 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1506 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1507 }
1508 }
1509}
1510
1511void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1512 // Always start with a clean state.
1513 mCurrentCookedState.clear();
1514
1515 // Apply stylus buttons to current raw state.
1516 applyExternalStylusButtonState(when);
1517
1518 // Handle policy on initial down or hover events.
1519 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1520 mCurrentRawState.rawPointerData.pointerCount != 0;
1521
1522 uint32_t policyFlags = 0;
1523 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1524 if (initialDown || buttonsPressed) {
1525 // If this is a touch screen, hide the pointer on an initial down.
Michael Wrightaff169e2020-07-02 18:30:52 +01001526 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 getContext()->fadePointer();
1528 }
1529
1530 if (mParameters.wake) {
1531 policyFlags |= POLICY_FLAG_WAKE;
1532 }
1533 }
1534
1535 // Consume raw off-screen touches before cooking pointer data.
1536 // If touches are consumed, subsequent code will not receive any pointer data.
1537 if (consumeRawTouches(when, policyFlags)) {
1538 mCurrentRawState.rawPointerData.clear();
1539 }
1540
1541 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1542 // with cooked pointer data that has the same ids and indices as the raw data.
1543 // The following code can use either the raw or cooked data, as needed.
1544 cookPointerData();
1545
1546 // Apply stylus pressure to current cooked state.
1547 applyExternalStylusTouchState(when);
1548
1549 // Synthesize key down from raw buttons if needed.
1550 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1551 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1552 mCurrentCookedState.buttonState);
1553
1554 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wrightaff169e2020-07-02 18:30:52 +01001555 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001556 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1557 uint32_t id = idBits.clearFirstMarkedBit();
1558 const RawPointerData::Pointer& pointer =
1559 mCurrentRawState.rawPointerData.pointerForId(id);
1560 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1561 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1562 mCurrentCookedState.stylusIdBits.markBit(id);
1563 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1564 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1565 mCurrentCookedState.fingerIdBits.markBit(id);
1566 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1567 mCurrentCookedState.mouseIdBits.markBit(id);
1568 }
1569 }
1570 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1571 uint32_t id = idBits.clearFirstMarkedBit();
1572 const RawPointerData::Pointer& pointer =
1573 mCurrentRawState.rawPointerData.pointerForId(id);
1574 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1575 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1576 mCurrentCookedState.stylusIdBits.markBit(id);
1577 }
1578 }
1579
1580 // Stylus takes precedence over all tools, then mouse, then finger.
1581 PointerUsage pointerUsage = mPointerUsage;
1582 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1583 mCurrentCookedState.mouseIdBits.clear();
1584 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001585 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1587 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001588 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1590 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001591 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 }
1593
1594 dispatchPointerUsage(when, policyFlags, pointerUsage);
1595 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001596 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001598 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1599 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600
1601 mPointerController->setButtonState(mCurrentRawState.buttonState);
1602 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1603 mCurrentCookedState.cookedPointerData.idToIndex,
1604 mCurrentCookedState.cookedPointerData.touchingIdBits,
1605 mViewport.displayId);
1606 }
1607
1608 if (!mCurrentMotionAborted) {
1609 dispatchButtonRelease(when, policyFlags);
1610 dispatchHoverExit(when, policyFlags);
1611 dispatchTouches(when, policyFlags);
1612 dispatchHoverEnterAndMove(when, policyFlags);
1613 dispatchButtonPress(when, policyFlags);
1614 }
1615
1616 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1617 mCurrentMotionAborted = false;
1618 }
1619 }
1620
1621 // Synthesize key up from raw buttons if needed.
1622 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1623 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1624 mCurrentCookedState.buttonState);
1625
1626 // Clear some transient state.
1627 mCurrentRawState.rawVScroll = 0;
1628 mCurrentRawState.rawHScroll = 0;
1629
1630 // Copy current touch to last touch in preparation for the next cycle.
1631 mLastRawState.copyFrom(mCurrentRawState);
1632 mLastCookedState.copyFrom(mCurrentCookedState);
1633}
1634
1635void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001636 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1638 }
1639}
1640
1641void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1642 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1643 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1644
1645 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1646 float pressure = mExternalStylusState.pressure;
1647 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1648 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1649 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1650 }
1651 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1652 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1653
1654 PointerProperties& properties =
1655 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1656 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1657 properties.toolType = mExternalStylusState.toolType;
1658 }
1659 }
1660}
1661
1662bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001663 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001664 return false;
1665 }
1666
1667 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1668 state.rawPointerData.pointerCount != 0;
1669 if (initialDown) {
1670 if (mExternalStylusState.pressure != 0.0f) {
1671#if DEBUG_STYLUS_FUSION
1672 ALOGD("Have both stylus and touch data, beginning fusion");
1673#endif
1674 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1675 } else if (timeout) {
1676#if DEBUG_STYLUS_FUSION
1677 ALOGD("Timeout expired, assuming touch is not a stylus.");
1678#endif
1679 resetExternalStylus();
1680 } else {
1681 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1682 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1683 }
1684#if DEBUG_STYLUS_FUSION
1685 ALOGD("No stylus data but stylus is connected, requesting timeout "
1686 "(%" PRId64 "ms)",
1687 mExternalStylusFusionTimeout);
1688#endif
1689 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1690 return true;
1691 }
1692 }
1693
1694 // Check if the stylus pointer has gone up.
1695 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1696#if DEBUG_STYLUS_FUSION
1697 ALOGD("Stylus pointer is going up");
1698#endif
1699 mExternalStylusId = -1;
1700 }
1701
1702 return false;
1703}
1704
1705void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001706 if (mDeviceMode == DeviceMode::POINTER) {
1707 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1709 }
Michael Wrightaff169e2020-07-02 18:30:52 +01001710 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001711 if (mExternalStylusFusionTimeout < when) {
1712 processRawTouches(true /*timeout*/);
1713 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1714 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1715 }
1716 }
1717}
1718
1719void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1720 mExternalStylusState.copyFrom(state);
1721 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1722 // We're either in the middle of a fused stream of data or we're waiting on data before
1723 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1724 // data.
1725 mExternalStylusDataPending = true;
1726 processRawTouches(false /*timeout*/);
1727 }
1728}
1729
1730bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1731 // Check for release of a virtual key.
1732 if (mCurrentVirtualKey.down) {
1733 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1734 // Pointer went up while virtual key was down.
1735 mCurrentVirtualKey.down = false;
1736 if (!mCurrentVirtualKey.ignored) {
1737#if DEBUG_VIRTUAL_KEYS
1738 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1739 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1740#endif
1741 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1742 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1743 }
1744 return true;
1745 }
1746
1747 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1748 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1749 const RawPointerData::Pointer& pointer =
1750 mCurrentRawState.rawPointerData.pointerForId(id);
1751 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1752 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1753 // Pointer is still within the space of the virtual key.
1754 return true;
1755 }
1756 }
1757
1758 // Pointer left virtual key area or another pointer also went down.
1759 // Send key cancellation but do not consume the touch yet.
1760 // This is useful when the user swipes through from the virtual key area
1761 // into the main display surface.
1762 mCurrentVirtualKey.down = false;
1763 if (!mCurrentVirtualKey.ignored) {
1764#if DEBUG_VIRTUAL_KEYS
1765 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1766 mCurrentVirtualKey.scanCode);
1767#endif
1768 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1769 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1770 AKEY_EVENT_FLAG_CANCELED);
1771 }
1772 }
1773
1774 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1775 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1776 // Pointer just went down. Check for virtual key press or off-screen touches.
1777 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1778 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
1779 if (!isPointInsideSurface(pointer.x, pointer.y)) {
1780 // If exactly one pointer went down, check for virtual key hit.
1781 // Otherwise we will drop the entire stroke.
1782 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1783 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1784 if (virtualKey) {
1785 mCurrentVirtualKey.down = true;
1786 mCurrentVirtualKey.downTime = when;
1787 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1788 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1789 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001790 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1791 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792
1793 if (!mCurrentVirtualKey.ignored) {
1794#if DEBUG_VIRTUAL_KEYS
1795 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1796 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1797#endif
1798 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1799 AKEY_EVENT_FLAG_FROM_SYSTEM |
1800 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1801 }
1802 }
1803 }
1804 return true;
1805 }
1806 }
1807
1808 // Disable all virtual key touches that happen within a short time interval of the
1809 // most recent touch within the screen area. The idea is to filter out stray
1810 // virtual key presses when interacting with the touch screen.
1811 //
1812 // Problems we're trying to solve:
1813 //
1814 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1815 // virtual key area that is implemented by a separate touch panel and accidentally
1816 // triggers a virtual key.
1817 //
1818 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1819 // area and accidentally triggers a virtual key. This often happens when virtual keys
1820 // are layed out below the screen near to where the on screen keyboard's space bar
1821 // is displayed.
1822 if (mConfig.virtualKeyQuietTime > 0 &&
1823 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001824 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001825 }
1826 return false;
1827}
1828
1829void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1830 int32_t keyEventAction, int32_t keyEventFlags) {
1831 int32_t keyCode = mCurrentVirtualKey.keyCode;
1832 int32_t scanCode = mCurrentVirtualKey.scanCode;
1833 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001834 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 policyFlags |= POLICY_FLAG_VIRTUAL;
1836
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001837 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1838 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1839 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 getListener()->notifyKey(&args);
1841}
1842
1843void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1844 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1845 if (!currentIdBits.isEmpty()) {
1846 int32_t metaState = getContext()->getGlobalMetaState();
1847 int32_t buttonState = mCurrentCookedState.buttonState;
1848 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1849 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1850 mCurrentCookedState.cookedPointerData.pointerProperties,
1851 mCurrentCookedState.cookedPointerData.pointerCoords,
1852 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1853 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1854 mCurrentMotionAborted = true;
1855 }
1856}
1857
1858void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1859 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1860 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1861 int32_t metaState = getContext()->getGlobalMetaState();
1862 int32_t buttonState = mCurrentCookedState.buttonState;
1863
1864 if (currentIdBits == lastIdBits) {
1865 if (!currentIdBits.isEmpty()) {
1866 // No pointer id changes so this is a move event.
1867 // The listener takes care of batching moves so we don't have to deal with that here.
1868 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1869 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1870 mCurrentCookedState.cookedPointerData.pointerProperties,
1871 mCurrentCookedState.cookedPointerData.pointerCoords,
1872 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1873 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1874 }
1875 } else {
1876 // There may be pointers going up and pointers going down and pointers moving
1877 // all at the same time.
1878 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1879 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1880 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1881 BitSet32 dispatchedIdBits(lastIdBits.value);
1882
1883 // Update last coordinates of pointers that have moved so that we observe the new
1884 // pointer positions at the same time as other pointers that have just gone up.
1885 bool moveNeeded =
1886 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1887 mCurrentCookedState.cookedPointerData.pointerCoords,
1888 mCurrentCookedState.cookedPointerData.idToIndex,
1889 mLastCookedState.cookedPointerData.pointerProperties,
1890 mLastCookedState.cookedPointerData.pointerCoords,
1891 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1892 if (buttonState != mLastCookedState.buttonState) {
1893 moveNeeded = true;
1894 }
1895
1896 // Dispatch pointer up events.
1897 while (!upIdBits.isEmpty()) {
1898 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhung65600042020-04-30 17:55:40 +08001899 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1900 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1901 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902 mLastCookedState.cookedPointerData.pointerProperties,
1903 mLastCookedState.cookedPointerData.pointerCoords,
1904 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1905 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1906 dispatchedIdBits.clearBit(upId);
arthurhung65600042020-04-30 17:55:40 +08001907 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 }
1909
1910 // Dispatch move events if any of the remaining pointers moved from their old locations.
1911 // Although applications receive new locations as part of individual pointer up
1912 // events, they do not generally handle them except when presented in a move event.
1913 if (moveNeeded && !moveIdBits.isEmpty()) {
1914 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1915 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1916 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1917 mCurrentCookedState.cookedPointerData.pointerCoords,
1918 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1919 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1920 }
1921
1922 // Dispatch pointer down events using the new pointer locations.
1923 while (!downIdBits.isEmpty()) {
1924 uint32_t downId = downIdBits.clearFirstMarkedBit();
1925 dispatchedIdBits.markBit(downId);
1926
1927 if (dispatchedIdBits.count() == 1) {
1928 // First pointer is going down. Set down time.
1929 mDownTime = when;
1930 }
1931
1932 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1933 metaState, buttonState, 0,
1934 mCurrentCookedState.cookedPointerData.pointerProperties,
1935 mCurrentCookedState.cookedPointerData.pointerCoords,
1936 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1937 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1938 }
1939 }
1940}
1941
1942void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1943 if (mSentHoverEnter &&
1944 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1945 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1946 int32_t metaState = getContext()->getGlobalMetaState();
1947 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1948 mLastCookedState.buttonState, 0,
1949 mLastCookedState.cookedPointerData.pointerProperties,
1950 mLastCookedState.cookedPointerData.pointerCoords,
1951 mLastCookedState.cookedPointerData.idToIndex,
1952 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1953 mOrientedYPrecision, mDownTime);
1954 mSentHoverEnter = false;
1955 }
1956}
1957
1958void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1959 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1960 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1961 int32_t metaState = getContext()->getGlobalMetaState();
1962 if (!mSentHoverEnter) {
1963 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1964 metaState, mCurrentRawState.buttonState, 0,
1965 mCurrentCookedState.cookedPointerData.pointerProperties,
1966 mCurrentCookedState.cookedPointerData.pointerCoords,
1967 mCurrentCookedState.cookedPointerData.idToIndex,
1968 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1969 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1970 mSentHoverEnter = true;
1971 }
1972
1973 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1974 mCurrentRawState.buttonState, 0,
1975 mCurrentCookedState.cookedPointerData.pointerProperties,
1976 mCurrentCookedState.cookedPointerData.pointerCoords,
1977 mCurrentCookedState.cookedPointerData.idToIndex,
1978 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1979 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1980 }
1981}
1982
1983void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1984 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1985 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1986 const int32_t metaState = getContext()->getGlobalMetaState();
1987 int32_t buttonState = mLastCookedState.buttonState;
1988 while (!releasedButtons.isEmpty()) {
1989 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1990 buttonState &= ~actionButton;
1991 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1992 actionButton, 0, metaState, buttonState, 0,
1993 mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
1996 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1997 }
1998}
1999
2000void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2001 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2002 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2003 const int32_t metaState = getContext()->getGlobalMetaState();
2004 int32_t buttonState = mLastCookedState.buttonState;
2005 while (!pressedButtons.isEmpty()) {
2006 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2007 buttonState |= actionButton;
2008 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2009 0, metaState, buttonState, 0,
2010 mCurrentCookedState.cookedPointerData.pointerProperties,
2011 mCurrentCookedState.cookedPointerData.pointerCoords,
2012 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2013 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2014 }
2015}
2016
2017const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2018 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2019 return cookedPointerData.touchingIdBits;
2020 }
2021 return cookedPointerData.hoveringIdBits;
2022}
2023
2024void TouchInputMapper::cookPointerData() {
2025 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2026
2027 mCurrentCookedState.cookedPointerData.clear();
2028 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2029 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2030 mCurrentRawState.rawPointerData.hoveringIdBits;
2031 mCurrentCookedState.cookedPointerData.touchingIdBits =
2032 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +08002033 mCurrentCookedState.cookedPointerData.canceledIdBits =
2034 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002035
2036 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2037 mCurrentCookedState.buttonState = 0;
2038 } else {
2039 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2040 }
2041
2042 // Walk through the the active pointers and map device coordinates onto
2043 // surface coordinates and adjust for display orientation.
2044 for (uint32_t i = 0; i < currentPointerCount; i++) {
2045 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2046
2047 // Size
2048 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2049 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002050 case Calibration::SizeCalibration::GEOMETRIC:
2051 case Calibration::SizeCalibration::DIAMETER:
2052 case Calibration::SizeCalibration::BOX:
2053 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2055 touchMajor = in.touchMajor;
2056 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2057 toolMajor = in.toolMajor;
2058 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2059 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2060 : in.touchMajor;
2061 } else if (mRawPointerAxes.touchMajor.valid) {
2062 toolMajor = touchMajor = in.touchMajor;
2063 toolMinor = touchMinor =
2064 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2065 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2066 : in.touchMajor;
2067 } else if (mRawPointerAxes.toolMajor.valid) {
2068 touchMajor = toolMajor = in.toolMajor;
2069 touchMinor = toolMinor =
2070 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2071 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2072 : in.toolMajor;
2073 } else {
2074 ALOG_ASSERT(false,
2075 "No touch or tool axes. "
2076 "Size calibration should have been resolved to NONE.");
2077 touchMajor = 0;
2078 touchMinor = 0;
2079 toolMajor = 0;
2080 toolMinor = 0;
2081 size = 0;
2082 }
2083
2084 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2085 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2086 if (touchingCount > 1) {
2087 touchMajor /= touchingCount;
2088 touchMinor /= touchingCount;
2089 toolMajor /= touchingCount;
2090 toolMinor /= touchingCount;
2091 size /= touchingCount;
2092 }
2093 }
2094
Michael Wrightaff169e2020-07-02 18:30:52 +01002095 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002096 touchMajor *= mGeometricScale;
2097 touchMinor *= mGeometricScale;
2098 toolMajor *= mGeometricScale;
2099 toolMinor *= mGeometricScale;
Michael Wrightaff169e2020-07-02 18:30:52 +01002100 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002101 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2102 touchMinor = touchMajor;
2103 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2104 toolMinor = toolMajor;
Michael Wrightaff169e2020-07-02 18:30:52 +01002105 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002106 touchMinor = touchMajor;
2107 toolMinor = toolMajor;
2108 }
2109
2110 mCalibration.applySizeScaleAndBias(&touchMajor);
2111 mCalibration.applySizeScaleAndBias(&touchMinor);
2112 mCalibration.applySizeScaleAndBias(&toolMajor);
2113 mCalibration.applySizeScaleAndBias(&toolMinor);
2114 size *= mSizeScale;
2115 break;
2116 default:
2117 touchMajor = 0;
2118 touchMinor = 0;
2119 toolMajor = 0;
2120 toolMinor = 0;
2121 size = 0;
2122 break;
2123 }
2124
2125 // Pressure
2126 float pressure;
2127 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002128 case Calibration::PressureCalibration::PHYSICAL:
2129 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 pressure = in.pressure * mPressureScale;
2131 break;
2132 default:
2133 pressure = in.isHovering ? 0 : 1;
2134 break;
2135 }
2136
2137 // Tilt and Orientation
2138 float tilt;
2139 float orientation;
2140 if (mHaveTilt) {
2141 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2142 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2143 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2144 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2145 } else {
2146 tilt = 0;
2147
2148 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002149 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002150 orientation = in.orientation * mOrientationScale;
2151 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002152 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2154 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2155 if (c1 != 0 || c2 != 0) {
2156 orientation = atan2f(c1, c2) * 0.5f;
2157 float confidence = hypotf(c1, c2);
2158 float scale = 1.0f + confidence / 16.0f;
2159 touchMajor *= scale;
2160 touchMinor /= scale;
2161 toolMajor *= scale;
2162 toolMinor /= scale;
2163 } else {
2164 orientation = 0;
2165 }
2166 break;
2167 }
2168 default:
2169 orientation = 0;
2170 }
2171 }
2172
2173 // Distance
2174 float distance;
2175 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002176 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177 distance = in.distance * mDistanceScale;
2178 break;
2179 default:
2180 distance = 0;
2181 }
2182
2183 // Coverage
2184 int32_t rawLeft, rawTop, rawRight, rawBottom;
2185 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002186 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2188 rawRight = in.toolMinor & 0x0000ffff;
2189 rawBottom = in.toolMajor & 0x0000ffff;
2190 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2191 break;
2192 default:
2193 rawLeft = rawTop = rawRight = rawBottom = 0;
2194 break;
2195 }
2196
2197 // Adjust X,Y coords for device calibration
2198 // TODO: Adjust coverage coords?
2199 float xTransformed = in.x, yTransformed = in.y;
2200 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002201 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002202
2203 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002204 float left, top, right, bottom;
2205
2206 switch (mSurfaceOrientation) {
2207 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2209 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2210 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2211 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2212 orientation -= M_PI_2;
2213 if (mOrientedRanges.haveOrientation &&
2214 orientation < mOrientedRanges.orientation.min) {
2215 orientation +=
2216 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2217 }
2218 break;
2219 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002220 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2221 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2222 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2223 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2224 orientation -= M_PI;
2225 if (mOrientedRanges.haveOrientation &&
2226 orientation < mOrientedRanges.orientation.min) {
2227 orientation +=
2228 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2229 }
2230 break;
2231 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2233 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2234 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2235 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2236 orientation += M_PI_2;
2237 if (mOrientedRanges.haveOrientation &&
2238 orientation > mOrientedRanges.orientation.max) {
2239 orientation -=
2240 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2241 }
2242 break;
2243 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2245 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2246 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2247 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2248 break;
2249 }
2250
2251 // Write output coords.
2252 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2253 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002254 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2255 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2257 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2258 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2259 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2260 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2261 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2262 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wrightaff169e2020-07-02 18:30:52 +01002263 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002264 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2265 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2267 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2268 } else {
2269 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2270 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2271 }
2272
2273 // Write output properties.
2274 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
2275 uint32_t id = in.id;
2276 properties.clear();
2277 properties.id = id;
2278 properties.toolType = in.toolType;
2279
2280 // Write id index.
2281 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
2282 }
2283}
2284
2285void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2286 PointerUsage pointerUsage) {
2287 if (pointerUsage != mPointerUsage) {
2288 abortPointerUsage(when, policyFlags);
2289 mPointerUsage = pointerUsage;
2290 }
2291
2292 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002293 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002294 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2295 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002296 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 dispatchPointerStylus(when, policyFlags);
2298 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002299 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300 dispatchPointerMouse(when, policyFlags);
2301 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002302 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 break;
2304 }
2305}
2306
2307void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2308 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002309 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002310 abortPointerGestures(when, policyFlags);
2311 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002312 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 abortPointerStylus(when, policyFlags);
2314 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002315 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002316 abortPointerMouse(when, policyFlags);
2317 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002318 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 break;
2320 }
2321
Michael Wrightaff169e2020-07-02 18:30:52 +01002322 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323}
2324
2325void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2326 // Update current gesture coordinates.
2327 bool cancelPreviousGesture, finishPreviousGesture;
2328 bool sendEvents =
2329 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2330 if (!sendEvents) {
2331 return;
2332 }
2333 if (finishPreviousGesture) {
2334 cancelPreviousGesture = false;
2335 }
2336
2337 // Update the pointer presentation and spots.
Michael Wrightaff169e2020-07-02 18:30:52 +01002338 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002339 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 if (finishPreviousGesture || cancelPreviousGesture) {
2341 mPointerController->clearSpots();
2342 }
2343
Michael Wrightaff169e2020-07-02 18:30:52 +01002344 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2346 mPointerGesture.currentGestureIdToIndex,
2347 mPointerGesture.currentGestureIdBits,
2348 mPointerController->getDisplayId());
2349 }
2350 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002351 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 }
2353
2354 // Show or hide the pointer if needed.
2355 switch (mPointerGesture.currentGestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002356 case PointerGesture::Mode::NEUTRAL:
2357 case PointerGesture::Mode::QUIET:
2358 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2359 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wright976db0c2020-07-02 00:00:29 +01002361 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 }
2363 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002364 case PointerGesture::Mode::TAP:
2365 case PointerGesture::Mode::TAP_DRAG:
2366 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2367 case PointerGesture::Mode::HOVER:
2368 case PointerGesture::Mode::PRESS:
2369 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 // Unfade the pointer when the current gesture manipulates the
2371 // area directly under the pointer.
Michael Wright976db0c2020-07-02 00:00:29 +01002372 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002374 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 // Fade the pointer when the current gesture manipulates a different
2376 // area and there are spots to guide the user experience.
Michael Wrightaff169e2020-07-02 18:30:52 +01002377 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002378 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002380 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 }
2382 break;
2383 }
2384
2385 // Send events!
2386 int32_t metaState = getContext()->getGlobalMetaState();
2387 int32_t buttonState = mCurrentCookedState.buttonState;
2388
2389 // Update last coordinates of pointers that have moved so that we observe the new
2390 // pointer positions at the same time as other pointers that have just gone up.
Michael Wrightaff169e2020-07-02 18:30:52 +01002391 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2392 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2393 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2394 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2395 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2396 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 bool moveNeeded = false;
2398 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2399 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2400 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2401 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2402 mPointerGesture.lastGestureIdBits.value);
2403 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2404 mPointerGesture.currentGestureCoords,
2405 mPointerGesture.currentGestureIdToIndex,
2406 mPointerGesture.lastGestureProperties,
2407 mPointerGesture.lastGestureCoords,
2408 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2409 if (buttonState != mLastCookedState.buttonState) {
2410 moveNeeded = true;
2411 }
2412 }
2413
2414 // Send motion events for all pointers that went up or were canceled.
2415 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2416 if (!dispatchedGestureIdBits.isEmpty()) {
2417 if (cancelPreviousGesture) {
2418 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2419 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2420 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2421 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2422 mPointerGesture.downTime);
2423
2424 dispatchedGestureIdBits.clear();
2425 } else {
2426 BitSet32 upGestureIdBits;
2427 if (finishPreviousGesture) {
2428 upGestureIdBits = dispatchedGestureIdBits;
2429 } else {
2430 upGestureIdBits.value =
2431 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2432 }
2433 while (!upGestureIdBits.isEmpty()) {
2434 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2435
2436 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2437 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2438 mPointerGesture.lastGestureProperties,
2439 mPointerGesture.lastGestureCoords,
2440 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2441 0, mPointerGesture.downTime);
2442
2443 dispatchedGestureIdBits.clearBit(id);
2444 }
2445 }
2446 }
2447
2448 // Send motion events for all pointers that moved.
2449 if (moveNeeded) {
2450 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2451 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2452 mPointerGesture.currentGestureProperties,
2453 mPointerGesture.currentGestureCoords,
2454 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2455 mPointerGesture.downTime);
2456 }
2457
2458 // Send motion events for all pointers that went down.
2459 if (down) {
2460 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2461 ~dispatchedGestureIdBits.value);
2462 while (!downGestureIdBits.isEmpty()) {
2463 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2464 dispatchedGestureIdBits.markBit(id);
2465
2466 if (dispatchedGestureIdBits.count() == 1) {
2467 mPointerGesture.downTime = when;
2468 }
2469
2470 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2471 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2472 mPointerGesture.currentGestureCoords,
2473 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2474 0, mPointerGesture.downTime);
2475 }
2476 }
2477
2478 // Send motion events for hover.
Michael Wrightaff169e2020-07-02 18:30:52 +01002479 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2481 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2482 mPointerGesture.currentGestureProperties,
2483 mPointerGesture.currentGestureCoords,
2484 mPointerGesture.currentGestureIdToIndex,
2485 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2486 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2487 // Synthesize a hover move event after all pointers go up to indicate that
2488 // the pointer is hovering again even if the user is not currently touching
2489 // the touch pad. This ensures that a view will receive a fresh hover enter
2490 // event after a tap.
2491 float x, y;
2492 mPointerController->getPosition(&x, &y);
2493
2494 PointerProperties pointerProperties;
2495 pointerProperties.clear();
2496 pointerProperties.id = 0;
2497 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2498
2499 PointerCoords pointerCoords;
2500 pointerCoords.clear();
2501 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2502 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2503
2504 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002505 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2506 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2507 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2508 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2509 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 getListener()->notifyMotion(&args);
2511 }
2512
2513 // Update state.
2514 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2515 if (!down) {
2516 mPointerGesture.lastGestureIdBits.clear();
2517 } else {
2518 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2519 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2520 uint32_t id = idBits.clearFirstMarkedBit();
2521 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2522 mPointerGesture.lastGestureProperties[index].copyFrom(
2523 mPointerGesture.currentGestureProperties[index]);
2524 mPointerGesture.lastGestureCoords[index].copyFrom(
2525 mPointerGesture.currentGestureCoords[index]);
2526 mPointerGesture.lastGestureIdToIndex[id] = index;
2527 }
2528 }
2529}
2530
2531void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2532 // Cancel previously dispatches pointers.
2533 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2534 int32_t metaState = getContext()->getGlobalMetaState();
2535 int32_t buttonState = mCurrentRawState.buttonState;
2536 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2537 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2538 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2539 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2540 0, 0, mPointerGesture.downTime);
2541 }
2542
2543 // Reset the current pointer gesture.
2544 mPointerGesture.reset();
2545 mPointerVelocityControl.reset();
2546
2547 // Remove any current spots.
2548 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01002549 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 mPointerController->clearSpots();
2551 }
2552}
2553
2554bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2555 bool* outFinishPreviousGesture, bool isTimeout) {
2556 *outCancelPreviousGesture = false;
2557 *outFinishPreviousGesture = false;
2558
2559 // Handle TAP timeout.
2560 if (isTimeout) {
2561#if DEBUG_GESTURES
2562 ALOGD("Gestures: Processing timeout");
2563#endif
2564
Michael Wrightaff169e2020-07-02 18:30:52 +01002565 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2567 // The tap/drag timeout has not yet expired.
2568 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2569 mConfig.pointerGestureTapDragInterval);
2570 } else {
2571 // The tap is finished.
2572#if DEBUG_GESTURES
2573 ALOGD("Gestures: TAP finished");
2574#endif
2575 *outFinishPreviousGesture = true;
2576
2577 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002578 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 mPointerGesture.currentGestureIdBits.clear();
2580
2581 mPointerVelocityControl.reset();
2582 return true;
2583 }
2584 }
2585
2586 // We did not handle this timeout.
2587 return false;
2588 }
2589
2590 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2591 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2592
2593 // Update the velocity tracker.
2594 {
2595 VelocityTracker::Position positions[MAX_POINTERS];
2596 uint32_t count = 0;
2597 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2598 uint32_t id = idBits.clearFirstMarkedBit();
2599 const RawPointerData::Pointer& pointer =
2600 mCurrentRawState.rawPointerData.pointerForId(id);
2601 positions[count].x = pointer.x * mPointerXMovementScale;
2602 positions[count].y = pointer.y * mPointerYMovementScale;
2603 }
2604 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2605 positions);
2606 }
2607
2608 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2609 // to NEUTRAL, then we should not generate tap event.
Michael Wrightaff169e2020-07-02 18:30:52 +01002610 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2611 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2612 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002613 mPointerGesture.resetTap();
2614 }
2615
2616 // Pick a new active touch id if needed.
2617 // Choose an arbitrary pointer that just went down, if there is one.
2618 // Otherwise choose an arbitrary remaining pointer.
2619 // This guarantees we always have an active touch id when there is at least one pointer.
2620 // We keep the same active touch id for as long as possible.
2621 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2622 int32_t activeTouchId = lastActiveTouchId;
2623 if (activeTouchId < 0) {
2624 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2625 activeTouchId = mPointerGesture.activeTouchId =
2626 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2627 mPointerGesture.firstTouchTime = when;
2628 }
2629 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2630 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2631 activeTouchId = mPointerGesture.activeTouchId =
2632 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2633 } else {
2634 activeTouchId = mPointerGesture.activeTouchId = -1;
2635 }
2636 }
2637
2638 // Determine whether we are in quiet time.
2639 bool isQuietTime = false;
2640 if (activeTouchId < 0) {
2641 mPointerGesture.resetQuietTime();
2642 } else {
2643 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2644 if (!isQuietTime) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002645 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2646 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2647 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002648 currentFingerCount < 2) {
2649 // Enter quiet time when exiting swipe or freeform state.
2650 // This is to prevent accidentally entering the hover state and flinging the
2651 // pointer when finishing a swipe and there is still one pointer left onscreen.
2652 isQuietTime = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01002653 } else if (mPointerGesture.lastGestureMode ==
2654 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2656 // Enter quiet time when releasing the button and there are still two or more
2657 // fingers down. This may indicate that one finger was used to press the button
2658 // but it has not gone up yet.
2659 isQuietTime = true;
2660 }
2661 if (isQuietTime) {
2662 mPointerGesture.quietTime = when;
2663 }
2664 }
2665 }
2666
2667 // Switch states based on button and pointer state.
2668 if (isQuietTime) {
2669 // Case 1: Quiet time. (QUIET)
2670#if DEBUG_GESTURES
2671 ALOGD("Gestures: QUIET for next %0.3fms",
2672 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2673#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002674 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002675 *outFinishPreviousGesture = true;
2676 }
2677
2678 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002679 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680 mPointerGesture.currentGestureIdBits.clear();
2681
2682 mPointerVelocityControl.reset();
2683 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2684 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2685 // The pointer follows the active touch point.
2686 // Emit DOWN, MOVE, UP events at the pointer location.
2687 //
2688 // Only the active touch matters; other fingers are ignored. This policy helps
2689 // to handle the case where the user places a second finger on the touch pad
2690 // to apply the necessary force to depress an integrated button below the surface.
2691 // We don't want the second finger to be delivered to applications.
2692 //
2693 // For this to work well, we need to make sure to track the pointer that is really
2694 // active. If the user first puts one finger down to click then adds another
2695 // finger to drag then the active pointer should switch to the finger that is
2696 // being dragged.
2697#if DEBUG_GESTURES
2698 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2699 "currentFingerCount=%d",
2700 activeTouchId, currentFingerCount);
2701#endif
2702 // Reset state when just starting.
Michael Wrightaff169e2020-07-02 18:30:52 +01002703 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002704 *outFinishPreviousGesture = true;
2705 mPointerGesture.activeGestureId = 0;
2706 }
2707
2708 // Switch pointers if needed.
2709 // Find the fastest pointer and follow it.
2710 if (activeTouchId >= 0 && currentFingerCount > 1) {
2711 int32_t bestId = -1;
2712 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2713 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2714 uint32_t id = idBits.clearFirstMarkedBit();
2715 float vx, vy;
2716 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2717 float speed = hypotf(vx, vy);
2718 if (speed > bestSpeed) {
2719 bestId = id;
2720 bestSpeed = speed;
2721 }
2722 }
2723 }
2724 if (bestId >= 0 && bestId != activeTouchId) {
2725 mPointerGesture.activeTouchId = activeTouchId = bestId;
2726#if DEBUG_GESTURES
2727 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2728 "bestId=%d, bestSpeed=%0.3f",
2729 bestId, bestSpeed);
2730#endif
2731 }
2732 }
2733
2734 float deltaX = 0, deltaY = 0;
2735 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2736 const RawPointerData::Pointer& currentPointer =
2737 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2738 const RawPointerData::Pointer& lastPointer =
2739 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2740 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2741 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2742
2743 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2744 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2745
2746 // Move the pointer using a relative motion.
2747 // When using spots, the click will occur at the position of the anchor
2748 // spot and all other spots will move there.
2749 mPointerController->move(deltaX, deltaY);
2750 } else {
2751 mPointerVelocityControl.reset();
2752 }
2753
2754 float x, y;
2755 mPointerController->getPosition(&x, &y);
2756
Michael Wrightaff169e2020-07-02 18:30:52 +01002757 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758 mPointerGesture.currentGestureIdBits.clear();
2759 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2760 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2761 mPointerGesture.currentGestureProperties[0].clear();
2762 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2763 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2764 mPointerGesture.currentGestureCoords[0].clear();
2765 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2766 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2767 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2768 } else if (currentFingerCount == 0) {
2769 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wrightaff169e2020-07-02 18:30:52 +01002770 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 *outFinishPreviousGesture = true;
2772 }
2773
2774 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2775 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2776 bool tapped = false;
Michael Wrightaff169e2020-07-02 18:30:52 +01002777 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2778 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 lastFingerCount == 1) {
2780 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2781 float x, y;
2782 mPointerController->getPosition(&x, &y);
2783 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2784 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2785#if DEBUG_GESTURES
2786 ALOGD("Gestures: TAP");
2787#endif
2788
2789 mPointerGesture.tapUpTime = when;
2790 getContext()->requestTimeoutAtTime(when +
2791 mConfig.pointerGestureTapDragInterval);
2792
2793 mPointerGesture.activeGestureId = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +01002794 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 mPointerGesture.currentGestureIdBits.clear();
2796 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2797 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2798 mPointerGesture.currentGestureProperties[0].clear();
2799 mPointerGesture.currentGestureProperties[0].id =
2800 mPointerGesture.activeGestureId;
2801 mPointerGesture.currentGestureProperties[0].toolType =
2802 AMOTION_EVENT_TOOL_TYPE_FINGER;
2803 mPointerGesture.currentGestureCoords[0].clear();
2804 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2805 mPointerGesture.tapX);
2806 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2807 mPointerGesture.tapY);
2808 mPointerGesture.currentGestureCoords[0]
2809 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2810
2811 tapped = true;
2812 } else {
2813#if DEBUG_GESTURES
2814 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2815 y - mPointerGesture.tapY);
2816#endif
2817 }
2818 } else {
2819#if DEBUG_GESTURES
2820 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2821 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2822 (when - mPointerGesture.tapDownTime) * 0.000001f);
2823 } else {
2824 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2825 }
2826#endif
2827 }
2828 }
2829
2830 mPointerVelocityControl.reset();
2831
2832 if (!tapped) {
2833#if DEBUG_GESTURES
2834 ALOGD("Gestures: NEUTRAL");
2835#endif
2836 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002837 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 mPointerGesture.currentGestureIdBits.clear();
2839 }
2840 } else if (currentFingerCount == 1) {
2841 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2842 // The pointer follows the active touch point.
2843 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2844 // When in TAP_DRAG, emit MOVE events at the pointer location.
2845 ALOG_ASSERT(activeTouchId >= 0);
2846
Michael Wrightaff169e2020-07-02 18:30:52 +01002847 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2848 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2850 float x, y;
2851 mPointerController->getPosition(&x, &y);
2852 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2853 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002854 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 } else {
2856#if DEBUG_GESTURES
2857 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2858 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2859#endif
2860 }
2861 } else {
2862#if DEBUG_GESTURES
2863 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2864 (when - mPointerGesture.tapUpTime) * 0.000001f);
2865#endif
2866 }
Michael Wrightaff169e2020-07-02 18:30:52 +01002867 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2868 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 }
2870
2871 float deltaX = 0, deltaY = 0;
2872 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2873 const RawPointerData::Pointer& currentPointer =
2874 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2875 const RawPointerData::Pointer& lastPointer =
2876 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2877 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2878 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2879
2880 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2881 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2882
2883 // Move the pointer using a relative motion.
2884 // When using spots, the hover or drag will occur at the position of the anchor spot.
2885 mPointerController->move(deltaX, deltaY);
2886 } else {
2887 mPointerVelocityControl.reset();
2888 }
2889
2890 bool down;
Michael Wrightaff169e2020-07-02 18:30:52 +01002891 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892#if DEBUG_GESTURES
2893 ALOGD("Gestures: TAP_DRAG");
2894#endif
2895 down = true;
2896 } else {
2897#if DEBUG_GESTURES
2898 ALOGD("Gestures: HOVER");
2899#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002900 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 *outFinishPreviousGesture = true;
2902 }
2903 mPointerGesture.activeGestureId = 0;
2904 down = false;
2905 }
2906
2907 float x, y;
2908 mPointerController->getPosition(&x, &y);
2909
2910 mPointerGesture.currentGestureIdBits.clear();
2911 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2912 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2913 mPointerGesture.currentGestureProperties[0].clear();
2914 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2915 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2916 mPointerGesture.currentGestureCoords[0].clear();
2917 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2919 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2920 down ? 1.0f : 0.0f);
2921
2922 if (lastFingerCount == 0 && currentFingerCount != 0) {
2923 mPointerGesture.resetTap();
2924 mPointerGesture.tapDownTime = when;
2925 mPointerGesture.tapX = x;
2926 mPointerGesture.tapY = y;
2927 }
2928 } else {
2929 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2930 // We need to provide feedback for each finger that goes down so we cannot wait
2931 // for the fingers to move before deciding what to do.
2932 //
2933 // The ambiguous case is deciding what to do when there are two fingers down but they
2934 // have not moved enough to determine whether they are part of a drag or part of a
2935 // freeform gesture, or just a press or long-press at the pointer location.
2936 //
2937 // When there are two fingers we start with the PRESS hypothesis and we generate a
2938 // down at the pointer location.
2939 //
2940 // When the two fingers move enough or when additional fingers are added, we make
2941 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2942 ALOG_ASSERT(activeTouchId >= 0);
2943
2944 bool settled = when >=
2945 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wrightaff169e2020-07-02 18:30:52 +01002946 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2947 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2948 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 *outFinishPreviousGesture = true;
2950 } else if (!settled && currentFingerCount > lastFingerCount) {
2951 // Additional pointers have gone down but not yet settled.
2952 // Reset the gesture.
2953#if DEBUG_GESTURES
2954 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2955 "settle time remaining %0.3fms",
2956 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2957 when) * 0.000001f);
2958#endif
2959 *outCancelPreviousGesture = true;
2960 } else {
2961 // Continue previous gesture.
2962 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2963 }
2964
2965 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002966 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 mPointerGesture.activeGestureId = 0;
2968 mPointerGesture.referenceIdBits.clear();
2969 mPointerVelocityControl.reset();
2970
2971 // Use the centroid and pointer location as the reference points for the gesture.
2972#if DEBUG_GESTURES
2973 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2974 "settle time remaining %0.3fms",
2975 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2976 when) * 0.000001f);
2977#endif
2978 mCurrentRawState.rawPointerData
2979 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2980 &mPointerGesture.referenceTouchY);
2981 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
2982 &mPointerGesture.referenceGestureY);
2983 }
2984
2985 // Clear the reference deltas for fingers not yet included in the reference calculation.
2986 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
2987 ~mPointerGesture.referenceIdBits.value);
2988 !idBits.isEmpty();) {
2989 uint32_t id = idBits.clearFirstMarkedBit();
2990 mPointerGesture.referenceDeltas[id].dx = 0;
2991 mPointerGesture.referenceDeltas[id].dy = 0;
2992 }
2993 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
2994
2995 // Add delta for all fingers and calculate a common movement delta.
2996 float commonDeltaX = 0, commonDeltaY = 0;
2997 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
2998 mCurrentCookedState.fingerIdBits.value);
2999 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3000 bool first = (idBits == commonIdBits);
3001 uint32_t id = idBits.clearFirstMarkedBit();
3002 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3003 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3004 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3005 delta.dx += cpd.x - lpd.x;
3006 delta.dy += cpd.y - lpd.y;
3007
3008 if (first) {
3009 commonDeltaX = delta.dx;
3010 commonDeltaY = delta.dy;
3011 } else {
3012 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3013 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3014 }
3015 }
3016
3017 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wrightaff169e2020-07-02 18:30:52 +01003018 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 float dist[MAX_POINTER_ID + 1];
3020 int32_t distOverThreshold = 0;
3021 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3022 uint32_t id = idBits.clearFirstMarkedBit();
3023 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3024 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3025 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3026 distOverThreshold += 1;
3027 }
3028 }
3029
3030 // Only transition when at least two pointers have moved further than
3031 // the minimum distance threshold.
3032 if (distOverThreshold >= 2) {
3033 if (currentFingerCount > 2) {
3034 // There are more than two pointers, switch to FREEFORM.
3035#if DEBUG_GESTURES
3036 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3037 currentFingerCount);
3038#endif
3039 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003040 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003041 } else {
3042 // There are exactly two pointers.
3043 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3044 uint32_t id1 = idBits.clearFirstMarkedBit();
3045 uint32_t id2 = idBits.firstMarkedBit();
3046 const RawPointerData::Pointer& p1 =
3047 mCurrentRawState.rawPointerData.pointerForId(id1);
3048 const RawPointerData::Pointer& p2 =
3049 mCurrentRawState.rawPointerData.pointerForId(id2);
3050 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3051 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3052 // There are two pointers but they are too far apart for a SWIPE,
3053 // switch to FREEFORM.
3054#if DEBUG_GESTURES
3055 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3056 mutualDistance, mPointerGestureMaxSwipeWidth);
3057#endif
3058 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003059 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 } else {
3061 // There are two pointers. Wait for both pointers to start moving
3062 // before deciding whether this is a SWIPE or FREEFORM gesture.
3063 float dist1 = dist[id1];
3064 float dist2 = dist[id2];
3065 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3066 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3067 // Calculate the dot product of the displacement vectors.
3068 // When the vectors are oriented in approximately the same direction,
3069 // the angle betweeen them is near zero and the cosine of the angle
3070 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3071 // mag(v2).
3072 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3073 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3074 float dx1 = delta1.dx * mPointerXZoomScale;
3075 float dy1 = delta1.dy * mPointerYZoomScale;
3076 float dx2 = delta2.dx * mPointerXZoomScale;
3077 float dy2 = delta2.dy * mPointerYZoomScale;
3078 float dot = dx1 * dx2 + dy1 * dy2;
3079 float cosine = dot / (dist1 * dist2); // denominator always > 0
3080 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3081 // Pointers are moving in the same direction. Switch to SWIPE.
3082#if DEBUG_GESTURES
3083 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3084 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3085 "cosine %0.3f >= %0.3f",
3086 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3087 mConfig.pointerGestureMultitouchMinDistance, cosine,
3088 mConfig.pointerGestureSwipeTransitionAngleCosine);
3089#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01003090 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003091 } else {
3092 // Pointers are moving in different directions. Switch to FREEFORM.
3093#if DEBUG_GESTURES
3094 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3095 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3096 "cosine %0.3f < %0.3f",
3097 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3098 mConfig.pointerGestureMultitouchMinDistance, cosine,
3099 mConfig.pointerGestureSwipeTransitionAngleCosine);
3100#endif
3101 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003102 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003103 }
3104 }
3105 }
3106 }
3107 }
Michael Wrightaff169e2020-07-02 18:30:52 +01003108 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003109 // Switch from SWIPE to FREEFORM if additional pointers go down.
3110 // Cancel previous gesture.
3111 if (currentFingerCount > 2) {
3112#if DEBUG_GESTURES
3113 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3114 currentFingerCount);
3115#endif
3116 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003117 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003118 }
3119 }
3120
3121 // Move the reference points based on the overall group motion of the fingers
3122 // except in PRESS mode while waiting for a transition to occur.
Michael Wrightaff169e2020-07-02 18:30:52 +01003123 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003124 (commonDeltaX || commonDeltaY)) {
3125 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3126 uint32_t id = idBits.clearFirstMarkedBit();
3127 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3128 delta.dx = 0;
3129 delta.dy = 0;
3130 }
3131
3132 mPointerGesture.referenceTouchX += commonDeltaX;
3133 mPointerGesture.referenceTouchY += commonDeltaY;
3134
3135 commonDeltaX *= mPointerXMovementScale;
3136 commonDeltaY *= mPointerYMovementScale;
3137
3138 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3139 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3140
3141 mPointerGesture.referenceGestureX += commonDeltaX;
3142 mPointerGesture.referenceGestureY += commonDeltaY;
3143 }
3144
3145 // Report gestures.
Michael Wrightaff169e2020-07-02 18:30:52 +01003146 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3147 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003148 // PRESS or SWIPE mode.
3149#if DEBUG_GESTURES
3150 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3151 "activeGestureId=%d, currentTouchPointerCount=%d",
3152 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3153#endif
3154 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3155
3156 mPointerGesture.currentGestureIdBits.clear();
3157 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3158 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3159 mPointerGesture.currentGestureProperties[0].clear();
3160 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3161 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3162 mPointerGesture.currentGestureCoords[0].clear();
3163 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3164 mPointerGesture.referenceGestureX);
3165 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3166 mPointerGesture.referenceGestureY);
3167 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightaff169e2020-07-02 18:30:52 +01003168 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003169 // FREEFORM mode.
3170#if DEBUG_GESTURES
3171 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3172 "activeGestureId=%d, currentTouchPointerCount=%d",
3173 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3174#endif
3175 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3176
3177 mPointerGesture.currentGestureIdBits.clear();
3178
3179 BitSet32 mappedTouchIdBits;
3180 BitSet32 usedGestureIdBits;
Michael Wrightaff169e2020-07-02 18:30:52 +01003181 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003182 // Initially, assign the active gesture id to the active touch point
3183 // if there is one. No other touch id bits are mapped yet.
3184 if (!*outCancelPreviousGesture) {
3185 mappedTouchIdBits.markBit(activeTouchId);
3186 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3187 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3188 mPointerGesture.activeGestureId;
3189 } else {
3190 mPointerGesture.activeGestureId = -1;
3191 }
3192 } else {
3193 // Otherwise, assume we mapped all touches from the previous frame.
3194 // Reuse all mappings that are still applicable.
3195 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3196 mCurrentCookedState.fingerIdBits.value;
3197 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3198
3199 // Check whether we need to choose a new active gesture id because the
3200 // current went went up.
3201 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3202 ~mCurrentCookedState.fingerIdBits.value);
3203 !upTouchIdBits.isEmpty();) {
3204 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3205 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3206 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3207 mPointerGesture.activeGestureId = -1;
3208 break;
3209 }
3210 }
3211 }
3212
3213#if DEBUG_GESTURES
3214 ALOGD("Gestures: FREEFORM follow up "
3215 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3216 "activeGestureId=%d",
3217 mappedTouchIdBits.value, usedGestureIdBits.value,
3218 mPointerGesture.activeGestureId);
3219#endif
3220
3221 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3222 for (uint32_t i = 0; i < currentFingerCount; i++) {
3223 uint32_t touchId = idBits.clearFirstMarkedBit();
3224 uint32_t gestureId;
3225 if (!mappedTouchIdBits.hasBit(touchId)) {
3226 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3227 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3228#if DEBUG_GESTURES
3229 ALOGD("Gestures: FREEFORM "
3230 "new mapping for touch id %d -> gesture id %d",
3231 touchId, gestureId);
3232#endif
3233 } else {
3234 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3235#if DEBUG_GESTURES
3236 ALOGD("Gestures: FREEFORM "
3237 "existing mapping for touch id %d -> gesture id %d",
3238 touchId, gestureId);
3239#endif
3240 }
3241 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3242 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3243
3244 const RawPointerData::Pointer& pointer =
3245 mCurrentRawState.rawPointerData.pointerForId(touchId);
3246 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3247 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3248 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3249
3250 mPointerGesture.currentGestureProperties[i].clear();
3251 mPointerGesture.currentGestureProperties[i].id = gestureId;
3252 mPointerGesture.currentGestureProperties[i].toolType =
3253 AMOTION_EVENT_TOOL_TYPE_FINGER;
3254 mPointerGesture.currentGestureCoords[i].clear();
3255 mPointerGesture.currentGestureCoords[i]
3256 .setAxisValue(AMOTION_EVENT_AXIS_X,
3257 mPointerGesture.referenceGestureX + deltaX);
3258 mPointerGesture.currentGestureCoords[i]
3259 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3260 mPointerGesture.referenceGestureY + deltaY);
3261 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3262 1.0f);
3263 }
3264
3265 if (mPointerGesture.activeGestureId < 0) {
3266 mPointerGesture.activeGestureId =
3267 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3268#if DEBUG_GESTURES
3269 ALOGD("Gestures: FREEFORM new "
3270 "activeGestureId=%d",
3271 mPointerGesture.activeGestureId);
3272#endif
3273 }
3274 }
3275 }
3276
3277 mPointerController->setButtonState(mCurrentRawState.buttonState);
3278
3279#if DEBUG_GESTURES
3280 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3281 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3282 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3283 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3284 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3285 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3286 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3287 uint32_t id = idBits.clearFirstMarkedBit();
3288 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3289 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3290 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3291 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3292 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3293 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3294 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3295 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3296 }
3297 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3298 uint32_t id = idBits.clearFirstMarkedBit();
3299 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3300 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3301 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3302 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3303 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3304 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3305 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3306 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3307 }
3308#endif
3309 return true;
3310}
3311
3312void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3313 mPointerSimple.currentCoords.clear();
3314 mPointerSimple.currentProperties.clear();
3315
3316 bool down, hovering;
3317 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3318 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3319 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3320 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3321 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3322 mPointerController->setPosition(x, y);
3323
3324 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3325 down = !hovering;
3326
3327 mPointerController->getPosition(&x, &y);
3328 mPointerSimple.currentCoords.copyFrom(
3329 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3330 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3331 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3332 mPointerSimple.currentProperties.id = 0;
3333 mPointerSimple.currentProperties.toolType =
3334 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3335 } else {
3336 down = false;
3337 hovering = false;
3338 }
3339
3340 dispatchPointerSimple(when, policyFlags, down, hovering);
3341}
3342
3343void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3344 abortPointerSimple(when, policyFlags);
3345}
3346
3347void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3348 mPointerSimple.currentCoords.clear();
3349 mPointerSimple.currentProperties.clear();
3350
3351 bool down, hovering;
3352 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3353 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3354 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3355 float deltaX = 0, deltaY = 0;
3356 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3357 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3358 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3359 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3360 mPointerXMovementScale;
3361 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3362 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3363 mPointerYMovementScale;
3364
3365 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3366 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3367
3368 mPointerController->move(deltaX, deltaY);
3369 } else {
3370 mPointerVelocityControl.reset();
3371 }
3372
3373 down = isPointerDown(mCurrentRawState.buttonState);
3374 hovering = !down;
3375
3376 float x, y;
3377 mPointerController->getPosition(&x, &y);
3378 mPointerSimple.currentCoords.copyFrom(
3379 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3380 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3381 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3382 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3383 hovering ? 0.0f : 1.0f);
3384 mPointerSimple.currentProperties.id = 0;
3385 mPointerSimple.currentProperties.toolType =
3386 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3387 } else {
3388 mPointerVelocityControl.reset();
3389
3390 down = false;
3391 hovering = false;
3392 }
3393
3394 dispatchPointerSimple(when, policyFlags, down, hovering);
3395}
3396
3397void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3398 abortPointerSimple(when, policyFlags);
3399
3400 mPointerVelocityControl.reset();
3401}
3402
3403void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3404 bool hovering) {
3405 int32_t metaState = getContext()->getGlobalMetaState();
3406 int32_t displayId = mViewport.displayId;
3407
3408 if (down || hovering) {
Michael Wright976db0c2020-07-02 00:00:29 +01003409 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003410 mPointerController->clearSpots();
3411 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wright976db0c2020-07-02 00:00:29 +01003412 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003413 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wright976db0c2020-07-02 00:00:29 +01003414 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415 }
3416 displayId = mPointerController->getDisplayId();
3417
3418 float xCursorPosition;
3419 float yCursorPosition;
3420 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3421
3422 if (mPointerSimple.down && !down) {
3423 mPointerSimple.down = false;
3424
3425 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003426 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3427 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 mLastRawState.buttonState, MotionClassification::NONE,
3429 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3430 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3431 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3432 /* videoFrames */ {});
3433 getListener()->notifyMotion(&args);
3434 }
3435
3436 if (mPointerSimple.hovering && !hovering) {
3437 mPointerSimple.hovering = false;
3438
3439 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003440 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3441 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3442 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003443 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3444 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3445 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3446 /* videoFrames */ {});
3447 getListener()->notifyMotion(&args);
3448 }
3449
3450 if (down) {
3451 if (!mPointerSimple.down) {
3452 mPointerSimple.down = true;
3453 mPointerSimple.downTime = when;
3454
3455 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003456 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003457 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3458 metaState, mCurrentRawState.buttonState,
3459 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3460 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3461 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3462 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3463 getListener()->notifyMotion(&args);
3464 }
3465
3466 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003467 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3468 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 mCurrentRawState.buttonState, MotionClassification::NONE,
3470 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3471 &mPointerSimple.currentCoords, mOrientedXPrecision,
3472 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3473 mPointerSimple.downTime, /* videoFrames */ {});
3474 getListener()->notifyMotion(&args);
3475 }
3476
3477 if (hovering) {
3478 if (!mPointerSimple.hovering) {
3479 mPointerSimple.hovering = true;
3480
3481 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003482 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3484 metaState, mCurrentRawState.buttonState,
3485 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3486 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3487 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3488 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3489 getListener()->notifyMotion(&args);
3490 }
3491
3492 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003493 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3494 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3495 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003496 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3497 &mPointerSimple.currentCoords, mOrientedXPrecision,
3498 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3499 mPointerSimple.downTime, /* videoFrames */ {});
3500 getListener()->notifyMotion(&args);
3501 }
3502
3503 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3504 float vscroll = mCurrentRawState.rawVScroll;
3505 float hscroll = mCurrentRawState.rawHScroll;
3506 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3507 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3508
3509 // Send scroll.
3510 PointerCoords pointerCoords;
3511 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3512 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3513 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3514
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003515 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3516 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 mCurrentRawState.buttonState, MotionClassification::NONE,
3518 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3519 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3520 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3521 /* videoFrames */ {});
3522 getListener()->notifyMotion(&args);
3523 }
3524
3525 // Save state.
3526 if (down || hovering) {
3527 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3528 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3529 } else {
3530 mPointerSimple.reset();
3531 }
3532}
3533
3534void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3535 mPointerSimple.currentCoords.clear();
3536 mPointerSimple.currentProperties.clear();
3537
3538 dispatchPointerSimple(when, policyFlags, false, false);
3539}
3540
3541void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3542 int32_t action, int32_t actionButton, int32_t flags,
3543 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3544 const PointerProperties* properties,
3545 const PointerCoords* coords, const uint32_t* idToIndex,
3546 BitSet32 idBits, int32_t changedId, float xPrecision,
3547 float yPrecision, nsecs_t downTime) {
3548 PointerCoords pointerCoords[MAX_POINTERS];
3549 PointerProperties pointerProperties[MAX_POINTERS];
3550 uint32_t pointerCount = 0;
3551 while (!idBits.isEmpty()) {
3552 uint32_t id = idBits.clearFirstMarkedBit();
3553 uint32_t index = idToIndex[id];
3554 pointerProperties[pointerCount].copyFrom(properties[index]);
3555 pointerCoords[pointerCount].copyFrom(coords[index]);
3556
3557 if (changedId >= 0 && id == uint32_t(changedId)) {
3558 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3559 }
3560
3561 pointerCount += 1;
3562 }
3563
3564 ALOG_ASSERT(pointerCount != 0);
3565
3566 if (changedId >= 0 && pointerCount == 1) {
3567 // Replace initial down and final up action.
3568 // We can compare the action without masking off the changed pointer index
3569 // because we know the index is 0.
3570 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3571 action = AMOTION_EVENT_ACTION_DOWN;
3572 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhung65600042020-04-30 17:55:40 +08003573 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3574 action = AMOTION_EVENT_ACTION_CANCEL;
3575 } else {
3576 action = AMOTION_EVENT_ACTION_UP;
3577 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578 } else {
3579 // Can't happen.
3580 ALOG_ASSERT(false);
3581 }
3582 }
3583 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3584 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wrightaff169e2020-07-02 18:30:52 +01003585 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3587 }
3588 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3589 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003590 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 std::for_each(frames.begin(), frames.end(),
3592 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003593 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3594 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3596 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3597 downTime, std::move(frames));
3598 getListener()->notifyMotion(&args);
3599}
3600
3601bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3602 const PointerCoords* inCoords,
3603 const uint32_t* inIdToIndex,
3604 PointerProperties* outProperties,
3605 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3606 BitSet32 idBits) const {
3607 bool changed = false;
3608 while (!idBits.isEmpty()) {
3609 uint32_t id = idBits.clearFirstMarkedBit();
3610 uint32_t inIndex = inIdToIndex[id];
3611 uint32_t outIndex = outIdToIndex[id];
3612
3613 const PointerProperties& curInProperties = inProperties[inIndex];
3614 const PointerCoords& curInCoords = inCoords[inIndex];
3615 PointerProperties& curOutProperties = outProperties[outIndex];
3616 PointerCoords& curOutCoords = outCoords[outIndex];
3617
3618 if (curInProperties != curOutProperties) {
3619 curOutProperties.copyFrom(curInProperties);
3620 changed = true;
3621 }
3622
3623 if (curInCoords != curOutCoords) {
3624 curOutCoords.copyFrom(curInCoords);
3625 changed = true;
3626 }
3627 }
3628 return changed;
3629}
3630
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631void TouchInputMapper::cancelTouch(nsecs_t when) {
3632 abortPointerUsage(when, 0 /*policyFlags*/);
3633 abortTouches(when, 0 /* policyFlags*/);
3634}
3635
Arthur Hung4197f6b2020-03-16 15:39:59 +08003636// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003637void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003638 // Scale to surface coordinate.
3639 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3640 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3641
3642 // Rotate to surface coordinate.
3643 // 0 - no swap and reverse.
3644 // 90 - swap x/y and reverse y.
3645 // 180 - reverse x, y.
3646 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003647 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003648 case DISPLAY_ORIENTATION_0:
3649 x = xScaled + mXTranslate;
3650 y = yScaled + mYTranslate;
3651 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003652 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003653 y = mSurfaceRight - xScaled;
3654 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003655 break;
3656 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003657 x = mSurfaceRight - xScaled;
3658 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003659 break;
3660 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003661 y = xScaled + mXTranslate;
3662 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003663 break;
3664 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003665 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003666 }
3667}
3668
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003669bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003670 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3671 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3672
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003673 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003674 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003676 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003677}
3678
3679const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3680 for (const VirtualKey& virtualKey : mVirtualKeys) {
3681#if DEBUG_VIRTUAL_KEYS
3682 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3683 "left=%d, top=%d, right=%d, bottom=%d",
3684 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3685 virtualKey.hitRight, virtualKey.hitBottom);
3686#endif
3687
3688 if (virtualKey.isHit(x, y)) {
3689 return &virtualKey;
3690 }
3691 }
3692
3693 return nullptr;
3694}
3695
3696void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3697 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3698 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3699
3700 current->rawPointerData.clearIdBits();
3701
3702 if (currentPointerCount == 0) {
3703 // No pointers to assign.
3704 return;
3705 }
3706
3707 if (lastPointerCount == 0) {
3708 // All pointers are new.
3709 for (uint32_t i = 0; i < currentPointerCount; i++) {
3710 uint32_t id = i;
3711 current->rawPointerData.pointers[i].id = id;
3712 current->rawPointerData.idToIndex[id] = i;
3713 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3714 }
3715 return;
3716 }
3717
3718 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3719 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3720 // Only one pointer and no change in count so it must have the same id as before.
3721 uint32_t id = last->rawPointerData.pointers[0].id;
3722 current->rawPointerData.pointers[0].id = id;
3723 current->rawPointerData.idToIndex[id] = 0;
3724 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3725 return;
3726 }
3727
3728 // General case.
3729 // We build a heap of squared euclidean distances between current and last pointers
3730 // associated with the current and last pointer indices. Then, we find the best
3731 // match (by distance) for each current pointer.
3732 // The pointers must have the same tool type but it is possible for them to
3733 // transition from hovering to touching or vice-versa while retaining the same id.
3734 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3735
3736 uint32_t heapSize = 0;
3737 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3738 currentPointerIndex++) {
3739 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3740 lastPointerIndex++) {
3741 const RawPointerData::Pointer& currentPointer =
3742 current->rawPointerData.pointers[currentPointerIndex];
3743 const RawPointerData::Pointer& lastPointer =
3744 last->rawPointerData.pointers[lastPointerIndex];
3745 if (currentPointer.toolType == lastPointer.toolType) {
3746 int64_t deltaX = currentPointer.x - lastPointer.x;
3747 int64_t deltaY = currentPointer.y - lastPointer.y;
3748
3749 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3750
3751 // Insert new element into the heap (sift up).
3752 heap[heapSize].currentPointerIndex = currentPointerIndex;
3753 heap[heapSize].lastPointerIndex = lastPointerIndex;
3754 heap[heapSize].distance = distance;
3755 heapSize += 1;
3756 }
3757 }
3758 }
3759
3760 // Heapify
3761 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3762 startIndex -= 1;
3763 for (uint32_t parentIndex = startIndex;;) {
3764 uint32_t childIndex = parentIndex * 2 + 1;
3765 if (childIndex >= heapSize) {
3766 break;
3767 }
3768
3769 if (childIndex + 1 < heapSize &&
3770 heap[childIndex + 1].distance < heap[childIndex].distance) {
3771 childIndex += 1;
3772 }
3773
3774 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3775 break;
3776 }
3777
3778 swap(heap[parentIndex], heap[childIndex]);
3779 parentIndex = childIndex;
3780 }
3781 }
3782
3783#if DEBUG_POINTER_ASSIGNMENT
3784 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3785 for (size_t i = 0; i < heapSize; i++) {
3786 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3787 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3788 }
3789#endif
3790
3791 // Pull matches out by increasing order of distance.
3792 // To avoid reassigning pointers that have already been matched, the loop keeps track
3793 // of which last and current pointers have been matched using the matchedXXXBits variables.
3794 // It also tracks the used pointer id bits.
3795 BitSet32 matchedLastBits(0);
3796 BitSet32 matchedCurrentBits(0);
3797 BitSet32 usedIdBits(0);
3798 bool first = true;
3799 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3800 while (heapSize > 0) {
3801 if (first) {
3802 // The first time through the loop, we just consume the root element of
3803 // the heap (the one with smallest distance).
3804 first = false;
3805 } else {
3806 // Previous iterations consumed the root element of the heap.
3807 // Pop root element off of the heap (sift down).
3808 heap[0] = heap[heapSize];
3809 for (uint32_t parentIndex = 0;;) {
3810 uint32_t childIndex = parentIndex * 2 + 1;
3811 if (childIndex >= heapSize) {
3812 break;
3813 }
3814
3815 if (childIndex + 1 < heapSize &&
3816 heap[childIndex + 1].distance < heap[childIndex].distance) {
3817 childIndex += 1;
3818 }
3819
3820 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3821 break;
3822 }
3823
3824 swap(heap[parentIndex], heap[childIndex]);
3825 parentIndex = childIndex;
3826 }
3827
3828#if DEBUG_POINTER_ASSIGNMENT
3829 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3830 for (size_t i = 0; i < heapSize; i++) {
3831 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3832 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3833 }
3834#endif
3835 }
3836
3837 heapSize -= 1;
3838
3839 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3840 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3841
3842 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3843 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3844
3845 matchedCurrentBits.markBit(currentPointerIndex);
3846 matchedLastBits.markBit(lastPointerIndex);
3847
3848 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3849 current->rawPointerData.pointers[currentPointerIndex].id = id;
3850 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3851 current->rawPointerData.markIdBit(id,
3852 current->rawPointerData.isHovering(
3853 currentPointerIndex));
3854 usedIdBits.markBit(id);
3855
3856#if DEBUG_POINTER_ASSIGNMENT
3857 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3858 ", distance=%" PRIu64,
3859 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3860#endif
3861 break;
3862 }
3863 }
3864
3865 // Assign fresh ids to pointers that were not matched in the process.
3866 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3867 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3868 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3869
3870 current->rawPointerData.pointers[currentPointerIndex].id = id;
3871 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3872 current->rawPointerData.markIdBit(id,
3873 current->rawPointerData.isHovering(currentPointerIndex));
3874
3875#if DEBUG_POINTER_ASSIGNMENT
3876 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3877#endif
3878 }
3879}
3880
3881int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3882 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3883 return AKEY_STATE_VIRTUAL;
3884 }
3885
3886 for (const VirtualKey& virtualKey : mVirtualKeys) {
3887 if (virtualKey.keyCode == keyCode) {
3888 return AKEY_STATE_UP;
3889 }
3890 }
3891
3892 return AKEY_STATE_UNKNOWN;
3893}
3894
3895int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3896 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3897 return AKEY_STATE_VIRTUAL;
3898 }
3899
3900 for (const VirtualKey& virtualKey : mVirtualKeys) {
3901 if (virtualKey.scanCode == scanCode) {
3902 return AKEY_STATE_UP;
3903 }
3904 }
3905
3906 return AKEY_STATE_UNKNOWN;
3907}
3908
3909bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3910 const int32_t* keyCodes, uint8_t* outFlags) {
3911 for (const VirtualKey& virtualKey : mVirtualKeys) {
3912 for (size_t i = 0; i < numCodes; i++) {
3913 if (virtualKey.keyCode == keyCodes[i]) {
3914 outFlags[i] = 1;
3915 }
3916 }
3917 }
3918
3919 return true;
3920}
3921
3922std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3923 if (mParameters.hasAssociatedDisplay) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003924 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003925 return std::make_optional(mPointerController->getDisplayId());
3926 } else {
3927 return std::make_optional(mViewport.displayId);
3928 }
3929 }
3930 return std::nullopt;
3931}
3932
3933} // namespace android