blob: e867c6f43aaf94568d42a08c31a6f40ad3b01c3f [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 Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-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;
arthurhungcc7f9802020-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();
arthurhungcc7f9802020-04-30 17:55:40 +0800144 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000145 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700146}
147
148void CookedPointerData::copyFrom(const CookedPointerData& other) {
149 pointerCount = other.pointerCount;
150 hoveringIdBits = other.hoveringIdBits;
151 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000152 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153
154 for (uint32_t i = 0; i < pointerCount; i++) {
155 pointerProperties[i].copyFrom(other.pointerProperties[i]);
156 pointerCoords[i].copyFrom(other.pointerCoords[i]);
157
158 int id = pointerProperties[i].id;
159 idToIndex[id] = other.idToIndex[id];
160 }
161}
162
163// --- TouchInputMapper ---
164
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800165TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
166 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700167 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100168 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800169 mRawSurfaceWidth(-1),
170 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700171 mSurfaceLeft(0),
172 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700173 mSurfaceRight(0),
174 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700175 mPhysicalWidth(-1),
176 mPhysicalHeight(-1),
177 mPhysicalLeft(0),
178 mPhysicalTop(0),
179 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
180
181TouchInputMapper::~TouchInputMapper() {}
182
183uint32_t TouchInputMapper::getSources() {
184 return mSource;
185}
186
187void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
188 InputMapper::populateDeviceInfo(info);
189
Michael Wright227c5542020-07-02 18:30:52 +0100190 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700191 info->addMotionRange(mOrientedRanges.x);
192 info->addMotionRange(mOrientedRanges.y);
193 info->addMotionRange(mOrientedRanges.pressure);
194
195 if (mOrientedRanges.haveSize) {
196 info->addMotionRange(mOrientedRanges.size);
197 }
198
199 if (mOrientedRanges.haveTouchSize) {
200 info->addMotionRange(mOrientedRanges.touchMajor);
201 info->addMotionRange(mOrientedRanges.touchMinor);
202 }
203
204 if (mOrientedRanges.haveToolSize) {
205 info->addMotionRange(mOrientedRanges.toolMajor);
206 info->addMotionRange(mOrientedRanges.toolMinor);
207 }
208
209 if (mOrientedRanges.haveOrientation) {
210 info->addMotionRange(mOrientedRanges.orientation);
211 }
212
213 if (mOrientedRanges.haveDistance) {
214 info->addMotionRange(mOrientedRanges.distance);
215 }
216
217 if (mOrientedRanges.haveTilt) {
218 info->addMotionRange(mOrientedRanges.tilt);
219 }
220
221 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
222 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
223 0.0f);
224 }
225 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
226 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
227 0.0f);
228 }
Michael Wright227c5542020-07-02 18:30:52 +0100229 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700230 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
231 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
232 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
233 x.fuzz, x.resolution);
234 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
235 y.fuzz, y.resolution);
236 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
237 x.fuzz, x.resolution);
238 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
239 y.fuzz, y.resolution);
240 }
241 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
242 }
243}
244
245void TouchInputMapper::dump(std::string& dump) {
246 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
247 dumpParameters(dump);
248 dumpVirtualKeys(dump);
249 dumpRawPointerAxes(dump);
250 dumpCalibration(dump);
251 dumpAffineTransformation(dump);
252 dumpSurface(dump);
253
254 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
255 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
256 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
257 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
258 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
259 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
260 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
261 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
262 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
263 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
264 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
265 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
266 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
267 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
268 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
269 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
270 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
271
272 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
273 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
274 mLastRawState.rawPointerData.pointerCount);
275 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
276 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
277 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
278 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
279 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
280 "toolType=%d, isHovering=%s\n",
281 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
282 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
283 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
284 pointer.distance, pointer.toolType, toString(pointer.isHovering));
285 }
286
287 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
288 mLastCookedState.buttonState);
289 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
290 mLastCookedState.cookedPointerData.pointerCount);
291 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
292 const PointerProperties& pointerProperties =
293 mLastCookedState.cookedPointerData.pointerProperties[i];
294 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000295 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
296 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
297 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700298 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
299 "toolType=%d, isHovering=%s\n",
300 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000301 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
302 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
304 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
305 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
306 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
307 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
308 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
309 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
310 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
311 pointerProperties.toolType,
312 toString(mLastCookedState.cookedPointerData.isHovering(i)));
313 }
314
315 dump += INDENT3 "Stylus Fusion:\n";
316 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
317 toString(mExternalStylusConnected));
318 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
319 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
320 mExternalStylusFusionTimeout);
321 dump += INDENT3 "External Stylus State:\n";
322 dumpStylusState(dump, mExternalStylusState);
323
Michael Wright227c5542020-07-02 18:30:52 +0100324 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700325 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
326 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
327 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
328 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
329 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
330 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
331 }
332}
333
334const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
335 switch (deviceMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100336 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 return "disabled";
Michael Wright227c5542020-07-02 18:30:52 +0100338 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 return "direct";
Michael Wright227c5542020-07-02 18:30:52 +0100340 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 return "unscaled";
Michael Wright227c5542020-07-02 18:30:52 +0100342 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 return "navigation";
Michael Wright227c5542020-07-02 18:30:52 +0100344 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345 return "pointer";
346 }
347 return "unknown";
348}
349
350void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
351 uint32_t changes) {
352 InputMapper::configure(when, config, changes);
353
354 mConfig = *config;
355
356 if (!changes) { // first time only
357 // Configure basic parameters.
358 configureParameters();
359
360 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mCursorScrollAccumulator.configure(getDeviceContext());
362 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363
364 // Configure absolute axis information.
365 configureRawPointerAxes();
366
367 // Prepare input device calibration.
368 parseCalibration();
369 resolveCalibration();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
373 // Update location calibration to reflect current settings
374 updateAffineTransformation();
375 }
376
377 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
378 // Update pointer speed.
379 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
380 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
381 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 }
383
384 bool resetNeeded = false;
385 if (!changes ||
386 (changes &
387 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800388 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
390 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
391 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
392 // Configure device sources, surface dimensions, orientation and
393 // scaling factors.
394 configureSurface(when, &resetNeeded);
395 }
396
397 if (changes && resetNeeded) {
398 // Send reset, unless this is the first time the device has been configured,
399 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800400 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800401 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 }
403}
404
405void TouchInputMapper::resolveExternalStylusPresence() {
406 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800407 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700408 mExternalStylusConnected = !devices.empty();
409
410 if (!mExternalStylusConnected) {
411 resetExternalStylus();
412 }
413}
414
415void TouchInputMapper::configureParameters() {
416 // Use the pointer presentation mode for devices that do not support distinct
417 // multitouch. The spot-based presentation relies on being able to accurately
418 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100420 ? Parameters::GestureMode::SINGLE_TOUCH
421 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700422
423 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
425 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700426 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100427 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100429 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700430 } else if (gestureModeString != "default") {
431 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
432 }
433 }
434
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800435 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100437 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800438 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800441 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
442 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 // The device is a cursor device with a touch pad attached.
444 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100445 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700446 } else {
447 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100448 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700449 }
450
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800451 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700452
453 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800454 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
455 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700456 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100459 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700460 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700462 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100463 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464 } else if (deviceTypeString != "default") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
466 }
467 }
468
Michael Wright227c5542020-07-02 18:30:52 +0100469 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800470 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
471 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 mParameters.hasAssociatedDisplay = false;
474 mParameters.associatedDisplayIsExternal = false;
475 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100476 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
477 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700478 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100479 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800480 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700481 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
483 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
485 }
486 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800487 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488 mParameters.hasAssociatedDisplay = true;
489 }
490
491 // Initial downs on external touch devices should wake the device.
492 // Normally we don't do this for internal touch screens to prevent them from waking
493 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 mParameters.wake = getDeviceContext().isExternal();
495 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496}
497
498void TouchInputMapper::dumpParameters(std::string& dump) {
499 dump += INDENT3 "Parameters:\n";
500
501 switch (mParameters.gestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +0100502 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700503 dump += INDENT4 "GestureMode: single-touch\n";
504 break;
Michael Wright227c5542020-07-02 18:30:52 +0100505 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700506 dump += INDENT4 "GestureMode: multi-touch\n";
507 break;
508 default:
509 assert(false);
510 }
511
512 switch (mParameters.deviceType) {
Michael Wright227c5542020-07-02 18:30:52 +0100513 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514 dump += INDENT4 "DeviceType: touchScreen\n";
515 break;
Michael Wright227c5542020-07-02 18:30:52 +0100516 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700517 dump += INDENT4 "DeviceType: touchPad\n";
518 break;
Michael Wright227c5542020-07-02 18:30:52 +0100519 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520 dump += INDENT4 "DeviceType: touchNavigation\n";
521 break;
Michael Wright227c5542020-07-02 18:30:52 +0100522 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700523 dump += INDENT4 "DeviceType: pointer\n";
524 break;
525 default:
526 ALOG_ASSERT(false);
527 }
528
529 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
530 "displayId='%s'\n",
531 toString(mParameters.hasAssociatedDisplay),
532 toString(mParameters.associatedDisplayIsExternal),
533 mParameters.uniqueDisplayId.c_str());
534 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
535}
536
537void TouchInputMapper::configureRawPointerAxes() {
538 mRawPointerAxes.clear();
539}
540
541void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
542 dump += INDENT3 "Raw Touch Axes:\n";
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
551 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
552 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
553 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
554 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
555 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
556}
557
558bool TouchInputMapper::hasExternalStylus() const {
559 return mExternalStylusConnected;
560}
561
562/**
563 * Determine which DisplayViewport to use.
564 * 1. If display port is specified, return the matching viewport. If matching viewport not
565 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800566 * 2. Always use the suggested viewport from WindowManagerService for pointers.
567 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800569 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 */
571std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800572 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800573 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 if (displayPort) {
575 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800576 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700577 }
578
Michael Wright227c5542020-07-02 18:30:52 +0100579 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800580 std::optional<DisplayViewport> viewport =
581 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
582 if (viewport) {
583 return viewport;
584 } else {
585 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
586 mConfig.defaultPointerDisplayId);
587 }
588 }
589
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700590 // Check if uniqueDisplayId is specified in idc file.
591 if (!mParameters.uniqueDisplayId.empty()) {
592 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
593 }
594
595 ViewportType viewportTypeToUse;
596 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100599 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600 }
601
602 std::optional<DisplayViewport> viewport =
603 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100604 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700605 ALOGW("Input device %s should be associated with external display, "
606 "fallback to internal one for the external viewport is not found.",
607 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100608 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700609 }
610
611 return viewport;
612 }
613
614 // No associated display, return a non-display viewport.
615 DisplayViewport newViewport;
616 // Raw width and height in the natural orientation.
617 int32_t rawWidth = mRawPointerAxes.getRawWidth();
618 int32_t rawHeight = mRawPointerAxes.getRawHeight();
619 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
620 return std::make_optional(newViewport);
621}
622
623void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100624 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700625
626 resolveExternalStylusPresence();
627
628 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100629 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800630 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700631 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100632 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700633 if (hasStylus()) {
634 mSource |= AINPUT_SOURCE_STYLUS;
635 }
Michael Wright227c5542020-07-02 18:30:52 +0100636 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700637 mParameters.hasAssociatedDisplay) {
638 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100639 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700640 if (hasStylus()) {
641 mSource |= AINPUT_SOURCE_STYLUS;
642 }
643 if (hasExternalStylus()) {
644 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
645 }
Michael Wright227c5542020-07-02 18:30:52 +0100646 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700647 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100648 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700649 } else {
650 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100651 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700652 }
653
654 // Ensure we have valid X and Y axes.
655 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
656 ALOGW("Touch device '%s' did not report support for X or Y axis! "
657 "The device will be inoperable.",
658 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100659 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700660 return;
661 }
662
663 // Get associated display dimensions.
664 std::optional<DisplayViewport> newViewport = findViewport();
665 if (!newViewport) {
666 ALOGI("Touch device '%s' could not query the properties of its associated "
667 "display. The device will be inoperable until the display size "
668 "becomes available.",
669 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100670 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700671 return;
672 }
673
674 // Raw width and height in the natural orientation.
675 int32_t rawWidth = mRawPointerAxes.getRawWidth();
676 int32_t rawHeight = mRawPointerAxes.getRawHeight();
677
678 bool viewportChanged = mViewport != *newViewport;
679 if (viewportChanged) {
680 mViewport = *newViewport;
681
Michael Wright227c5542020-07-02 18:30:52 +0100682 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700683 // Convert rotated viewport to natural surface coordinates.
684 int32_t naturalLogicalWidth, naturalLogicalHeight;
685 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
686 int32_t naturalPhysicalLeft, naturalPhysicalTop;
687 int32_t naturalDeviceWidth, naturalDeviceHeight;
688 switch (mViewport.orientation) {
689 case DISPLAY_ORIENTATION_90:
690 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
691 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
692 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
693 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800694 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700695 naturalPhysicalTop = mViewport.physicalLeft;
696 naturalDeviceWidth = mViewport.deviceHeight;
697 naturalDeviceHeight = mViewport.deviceWidth;
698 break;
699 case DISPLAY_ORIENTATION_180:
700 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
701 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
702 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
703 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
704 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
705 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
706 naturalDeviceWidth = mViewport.deviceWidth;
707 naturalDeviceHeight = mViewport.deviceHeight;
708 break;
709 case DISPLAY_ORIENTATION_270:
710 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
711 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
712 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
713 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
714 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800715 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700716 naturalDeviceWidth = mViewport.deviceHeight;
717 naturalDeviceHeight = mViewport.deviceWidth;
718 break;
719 case DISPLAY_ORIENTATION_0:
720 default:
721 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
722 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
723 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
724 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
725 naturalPhysicalLeft = mViewport.physicalLeft;
726 naturalPhysicalTop = mViewport.physicalTop;
727 naturalDeviceWidth = mViewport.deviceWidth;
728 naturalDeviceHeight = mViewport.deviceHeight;
729 break;
730 }
731
732 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
733 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
734 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
735 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
736 }
737
738 mPhysicalWidth = naturalPhysicalWidth;
739 mPhysicalHeight = naturalPhysicalHeight;
740 mPhysicalLeft = naturalPhysicalLeft;
741 mPhysicalTop = naturalPhysicalTop;
742
Arthur Hung4197f6b2020-03-16 15:39:59 +0800743 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
744 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700745 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
746 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800747 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
748 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700749
750 mSurfaceOrientation =
751 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
752 } else {
753 mPhysicalWidth = rawWidth;
754 mPhysicalHeight = rawHeight;
755 mPhysicalLeft = 0;
756 mPhysicalTop = 0;
757
Arthur Hung4197f6b2020-03-16 15:39:59 +0800758 mRawSurfaceWidth = rawWidth;
759 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700760 mSurfaceLeft = 0;
761 mSurfaceTop = 0;
762 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
763 }
764 }
765
766 // If moving between pointer modes, need to reset some state.
767 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
768 if (deviceModeChanged) {
769 mOrientedRanges.clear();
770 }
771
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800772 // Create pointer controller if needed.
Michael Wright227c5542020-07-02 18:30:52 +0100773 if (mDeviceMode == DeviceMode::POINTER ||
774 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800775 if (mPointerController == nullptr) {
776 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700777 }
778 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100779 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700780 }
781
782 if (viewportChanged || deviceModeChanged) {
783 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
784 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800785 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700786 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
787
788 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800789 mXScale = float(mRawSurfaceWidth) / rawWidth;
790 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 mXTranslate = -mSurfaceLeft;
792 mYTranslate = -mSurfaceTop;
793 mXPrecision = 1.0f / mXScale;
794 mYPrecision = 1.0f / mYScale;
795
796 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
797 mOrientedRanges.x.source = mSource;
798 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
799 mOrientedRanges.y.source = mSource;
800
801 configureVirtualKeys();
802
803 // Scale factor for terms that are not oriented in a particular axis.
804 // If the pixels are square then xScale == yScale otherwise we fake it
805 // by choosing an average.
806 mGeometricScale = avg(mXScale, mYScale);
807
808 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800809 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700810
811 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100812 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700813 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
814 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
815 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
816 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
817 } else {
818 mSizeScale = 0.0f;
819 }
820
821 mOrientedRanges.haveTouchSize = true;
822 mOrientedRanges.haveToolSize = true;
823 mOrientedRanges.haveSize = true;
824
825 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
826 mOrientedRanges.touchMajor.source = mSource;
827 mOrientedRanges.touchMajor.min = 0;
828 mOrientedRanges.touchMajor.max = diagonalSize;
829 mOrientedRanges.touchMajor.flat = 0;
830 mOrientedRanges.touchMajor.fuzz = 0;
831 mOrientedRanges.touchMajor.resolution = 0;
832
833 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
834 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
835
836 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
837 mOrientedRanges.toolMajor.source = mSource;
838 mOrientedRanges.toolMajor.min = 0;
839 mOrientedRanges.toolMajor.max = diagonalSize;
840 mOrientedRanges.toolMajor.flat = 0;
841 mOrientedRanges.toolMajor.fuzz = 0;
842 mOrientedRanges.toolMajor.resolution = 0;
843
844 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
845 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
846
847 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
848 mOrientedRanges.size.source = mSource;
849 mOrientedRanges.size.min = 0;
850 mOrientedRanges.size.max = 1.0;
851 mOrientedRanges.size.flat = 0;
852 mOrientedRanges.size.fuzz = 0;
853 mOrientedRanges.size.resolution = 0;
854 } else {
855 mSizeScale = 0.0f;
856 }
857
858 // Pressure factors.
859 mPressureScale = 0;
860 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100861 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
862 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700863 if (mCalibration.havePressureScale) {
864 mPressureScale = mCalibration.pressureScale;
865 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
866 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
867 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
868 }
869 }
870
871 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
872 mOrientedRanges.pressure.source = mSource;
873 mOrientedRanges.pressure.min = 0;
874 mOrientedRanges.pressure.max = pressureMax;
875 mOrientedRanges.pressure.flat = 0;
876 mOrientedRanges.pressure.fuzz = 0;
877 mOrientedRanges.pressure.resolution = 0;
878
879 // Tilt
880 mTiltXCenter = 0;
881 mTiltXScale = 0;
882 mTiltYCenter = 0;
883 mTiltYScale = 0;
884 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
885 if (mHaveTilt) {
886 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
887 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
888 mTiltXScale = M_PI / 180;
889 mTiltYScale = M_PI / 180;
890
891 mOrientedRanges.haveTilt = true;
892
893 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
894 mOrientedRanges.tilt.source = mSource;
895 mOrientedRanges.tilt.min = 0;
896 mOrientedRanges.tilt.max = M_PI_2;
897 mOrientedRanges.tilt.flat = 0;
898 mOrientedRanges.tilt.fuzz = 0;
899 mOrientedRanges.tilt.resolution = 0;
900 }
901
902 // Orientation
903 mOrientationScale = 0;
904 if (mHaveTilt) {
905 mOrientedRanges.haveOrientation = true;
906
907 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
908 mOrientedRanges.orientation.source = mSource;
909 mOrientedRanges.orientation.min = -M_PI;
910 mOrientedRanges.orientation.max = M_PI;
911 mOrientedRanges.orientation.flat = 0;
912 mOrientedRanges.orientation.fuzz = 0;
913 mOrientedRanges.orientation.resolution = 0;
914 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100915 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100917 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 if (mRawPointerAxes.orientation.valid) {
919 if (mRawPointerAxes.orientation.maxValue > 0) {
920 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
921 } else if (mRawPointerAxes.orientation.minValue < 0) {
922 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
923 } else {
924 mOrientationScale = 0;
925 }
926 }
927 }
928
929 mOrientedRanges.haveOrientation = true;
930
931 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
932 mOrientedRanges.orientation.source = mSource;
933 mOrientedRanges.orientation.min = -M_PI_2;
934 mOrientedRanges.orientation.max = M_PI_2;
935 mOrientedRanges.orientation.flat = 0;
936 mOrientedRanges.orientation.fuzz = 0;
937 mOrientedRanges.orientation.resolution = 0;
938 }
939
940 // Distance
941 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100942 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
943 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700944 if (mCalibration.haveDistanceScale) {
945 mDistanceScale = mCalibration.distanceScale;
946 } else {
947 mDistanceScale = 1.0f;
948 }
949 }
950
951 mOrientedRanges.haveDistance = true;
952
953 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
954 mOrientedRanges.distance.source = mSource;
955 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
956 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
957 mOrientedRanges.distance.flat = 0;
958 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
959 mOrientedRanges.distance.resolution = 0;
960 }
961
962 // Compute oriented precision, scales and ranges.
963 // Note that the maximum value reported is an inclusive maximum value so it is one
964 // unit less than the total width or height of surface.
965 switch (mSurfaceOrientation) {
966 case DISPLAY_ORIENTATION_90:
967 case DISPLAY_ORIENTATION_270:
968 mOrientedXPrecision = mYPrecision;
969 mOrientedYPrecision = mXPrecision;
970
971 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800972 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 mOrientedRanges.x.flat = 0;
974 mOrientedRanges.x.fuzz = 0;
975 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
976
977 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800978 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700979 mOrientedRanges.y.flat = 0;
980 mOrientedRanges.y.fuzz = 0;
981 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
982 break;
983
984 default:
985 mOrientedXPrecision = mXPrecision;
986 mOrientedYPrecision = mYPrecision;
987
988 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800989 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 mOrientedRanges.x.flat = 0;
991 mOrientedRanges.x.fuzz = 0;
992 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
993
994 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800995 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996 mOrientedRanges.y.flat = 0;
997 mOrientedRanges.y.fuzz = 0;
998 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
999 break;
1000 }
1001
1002 // Location
1003 updateAffineTransformation();
1004
Michael Wright227c5542020-07-02 18:30:52 +01001005 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001006 // Compute pointer gesture detection parameters.
1007 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001008 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009
1010 // Scale movements such that one whole swipe of the touch pad covers a
1011 // given area relative to the diagonal size of the display when no acceleration
1012 // is applied.
1013 // Assume that the touch pad has a square aspect ratio such that movements in
1014 // X and Y of the same number of raw units cover the same physical distance.
1015 mPointerXMovementScale =
1016 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1017 mPointerYMovementScale = mPointerXMovementScale;
1018
1019 // Scale zooms to cover a smaller range of the display than movements do.
1020 // This value determines the area around the pointer that is affected by freeform
1021 // pointer gestures.
1022 mPointerXZoomScale =
1023 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1024 mPointerYZoomScale = mPointerXZoomScale;
1025
1026 // Max width between pointers to detect a swipe gesture is more than some fraction
1027 // of the diagonal axis of the touch pad. Touches that are wider than this are
1028 // translated into freeform gestures.
1029 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1030
1031 // Abort current pointer usages because the state has changed.
1032 abortPointerUsage(when, 0 /*policyFlags*/);
1033 }
1034
1035 // Inform the dispatcher about the changes.
1036 *outResetNeeded = true;
1037 bumpGeneration();
1038 }
1039}
1040
1041void TouchInputMapper::dumpSurface(std::string& dump) {
1042 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001043 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1044 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001045 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1046 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001047 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1048 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1050 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1051 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1052 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1053 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1054}
1055
1056void TouchInputMapper::configureVirtualKeys() {
1057 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001058 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001059
1060 mVirtualKeys.clear();
1061
1062 if (virtualKeyDefinitions.size() == 0) {
1063 return;
1064 }
1065
1066 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1067 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1068 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1069 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1070
1071 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1072 VirtualKey virtualKey;
1073
1074 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1075 int32_t keyCode;
1076 int32_t dummyKeyMetaState;
1077 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001078 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1079 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1081 continue; // drop the key
1082 }
1083
1084 virtualKey.keyCode = keyCode;
1085 virtualKey.flags = flags;
1086
1087 // convert the key definition's display coordinates into touch coordinates for a hit box
1088 int32_t halfWidth = virtualKeyDefinition.width / 2;
1089 int32_t halfHeight = virtualKeyDefinition.height / 2;
1090
1091 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001092 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001093 touchScreenLeft;
1094 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001095 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001097 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1098 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001099 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001100 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1101 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001102 touchScreenTop;
1103 mVirtualKeys.push_back(virtualKey);
1104 }
1105}
1106
1107void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1108 if (!mVirtualKeys.empty()) {
1109 dump += INDENT3 "Virtual Keys:\n";
1110
1111 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1112 const VirtualKey& virtualKey = mVirtualKeys[i];
1113 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1114 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1115 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1116 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1117 }
1118 }
1119}
1120
1121void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001122 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 Calibration& out = mCalibration;
1124
1125 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001126 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 String8 sizeCalibrationString;
1128 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1129 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001132 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString != "default") {
1140 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1141 }
1142 }
1143
1144 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1145 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1146 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1147
1148 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001149 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001150 String8 pressureCalibrationString;
1151 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1152 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001153 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001155 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001156 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001157 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158 } else if (pressureCalibrationString != "default") {
1159 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1160 pressureCalibrationString.string());
1161 }
1162 }
1163
1164 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1165
1166 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 String8 orientationCalibrationString;
1169 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1170 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (orientationCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1178 orientationCalibrationString.string());
1179 }
1180 }
1181
1182 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 String8 distanceCalibrationString;
1185 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1186 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (distanceCalibrationString != "default") {
1191 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1192 distanceCalibrationString.string());
1193 }
1194 }
1195
1196 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1197
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 String8 coverageCalibrationString;
1200 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1201 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (coverageCalibrationString != "default") {
1206 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1207 coverageCalibrationString.string());
1208 }
1209 }
1210}
1211
1212void TouchInputMapper::resolveCalibration() {
1213 // Size
1214 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001215 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1216 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 }
1218 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001219 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 }
1221
1222 // Pressure
1223 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001224 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1225 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 }
1227 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001228 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230
1231 // Orientation
1232 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001233 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1234 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001237 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239
1240 // Distance
1241 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001242 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1243 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001246 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248
1249 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001250 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1251 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253}
1254
1255void TouchInputMapper::dumpCalibration(std::string& dump) {
1256 dump += INDENT3 "Calibration:\n";
1257
1258 // Size
1259 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001260 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001261 dump += INDENT4 "touch.size.calibration: none\n";
1262 break;
Michael Wright227c5542020-07-02 18:30:52 +01001263 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 dump += INDENT4 "touch.size.calibration: geometric\n";
1265 break;
Michael Wright227c5542020-07-02 18:30:52 +01001266 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 dump += INDENT4 "touch.size.calibration: diameter\n";
1268 break;
Michael Wright227c5542020-07-02 18:30:52 +01001269 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270 dump += INDENT4 "touch.size.calibration: box\n";
1271 break;
Michael Wright227c5542020-07-02 18:30:52 +01001272 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 dump += INDENT4 "touch.size.calibration: area\n";
1274 break;
1275 default:
1276 ALOG_ASSERT(false);
1277 }
1278
1279 if (mCalibration.haveSizeScale) {
1280 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1281 }
1282
1283 if (mCalibration.haveSizeBias) {
1284 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1285 }
1286
1287 if (mCalibration.haveSizeIsSummed) {
1288 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1289 toString(mCalibration.sizeIsSummed));
1290 }
1291
1292 // Pressure
1293 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001294 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.pressure.calibration: none\n";
1296 break;
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.pressure.calibration: physical\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1302 break;
1303 default:
1304 ALOG_ASSERT(false);
1305 }
1306
1307 if (mCalibration.havePressureScale) {
1308 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1309 }
1310
1311 // Orientation
1312 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.orientation.calibration: none\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.orientation.calibration: vector\n";
1321 break;
1322 default:
1323 ALOG_ASSERT(false);
1324 }
1325
1326 // Distance
1327 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.distance.calibration: none\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.distance.calibration: scaled\n";
1333 break;
1334 default:
1335 ALOG_ASSERT(false);
1336 }
1337
1338 if (mCalibration.haveDistanceScale) {
1339 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1340 }
1341
1342 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.coverage.calibration: none\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.coverage.calibration: box\n";
1348 break;
1349 default:
1350 ALOG_ASSERT(false);
1351 }
1352}
1353
1354void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1355 dump += INDENT3 "Affine Transformation:\n";
1356
1357 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1358 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1359 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1360 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1361 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1362 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1363}
1364
1365void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001366 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001367 mSurfaceOrientation);
1368}
1369
1370void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001371 mCursorButtonAccumulator.reset(getDeviceContext());
1372 mCursorScrollAccumulator.reset(getDeviceContext());
1373 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374
1375 mPointerVelocityControl.reset();
1376 mWheelXVelocityControl.reset();
1377 mWheelYVelocityControl.reset();
1378
1379 mRawStatesPending.clear();
1380 mCurrentRawState.clear();
1381 mCurrentCookedState.clear();
1382 mLastRawState.clear();
1383 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001384 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001385 mSentHoverEnter = false;
1386 mHavePointerIds = false;
1387 mCurrentMotionAborted = false;
1388 mDownTime = 0;
1389
1390 mCurrentVirtualKey.down = false;
1391
1392 mPointerGesture.reset();
1393 mPointerSimple.reset();
1394 resetExternalStylus();
1395
1396 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001397 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mPointerController->clearSpots();
1399 }
1400
1401 InputMapper::reset(when);
1402}
1403
1404void TouchInputMapper::resetExternalStylus() {
1405 mExternalStylusState.clear();
1406 mExternalStylusId = -1;
1407 mExternalStylusFusionTimeout = LLONG_MAX;
1408 mExternalStylusDataPending = false;
1409}
1410
1411void TouchInputMapper::clearStylusDataPendingFlags() {
1412 mExternalStylusDataPending = false;
1413 mExternalStylusFusionTimeout = LLONG_MAX;
1414}
1415
1416void TouchInputMapper::process(const RawEvent* rawEvent) {
1417 mCursorButtonAccumulator.process(rawEvent);
1418 mCursorScrollAccumulator.process(rawEvent);
1419 mTouchButtonAccumulator.process(rawEvent);
1420
1421 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1422 sync(rawEvent->when);
1423 }
1424}
1425
1426void TouchInputMapper::sync(nsecs_t when) {
1427 const RawState* last =
1428 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1429
1430 // Push a new state.
1431 mRawStatesPending.emplace_back();
1432
1433 RawState* next = &mRawStatesPending.back();
1434 next->clear();
1435 next->when = when;
1436
1437 // Sync button state.
1438 next->buttonState =
1439 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1440
1441 // Sync scroll
1442 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1443 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1444 mCursorScrollAccumulator.finishSync();
1445
1446 // Sync touch
1447 syncTouch(when, next);
1448
1449 // Assign pointer ids.
1450 if (!mHavePointerIds) {
1451 assignPointerIds(last, next);
1452 }
1453
1454#if DEBUG_RAW_EVENTS
1455 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001456 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001457 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1458 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhungcc7f9802020-04-30 17:55:40 +08001459 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1460 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001461#endif
1462
1463 processRawTouches(false /*timeout*/);
1464}
1465
1466void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001467 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468 // Drop all input if the device is disabled.
1469 mCurrentRawState.clear();
1470 mRawStatesPending.clear();
1471 return;
1472 }
1473
1474 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1475 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1476 // touching the current state will only observe the events that have been dispatched to the
1477 // rest of the pipeline.
1478 const size_t N = mRawStatesPending.size();
1479 size_t count;
1480 for (count = 0; count < N; count++) {
1481 const RawState& next = mRawStatesPending[count];
1482
1483 // A failure to assign the stylus id means that we're waiting on stylus data
1484 // and so should defer the rest of the pipeline.
1485 if (assignExternalStylusId(next, timeout)) {
1486 break;
1487 }
1488
1489 // All ready to go.
1490 clearStylusDataPendingFlags();
1491 mCurrentRawState.copyFrom(next);
1492 if (mCurrentRawState.when < mLastRawState.when) {
1493 mCurrentRawState.when = mLastRawState.when;
1494 }
1495 cookAndDispatch(mCurrentRawState.when);
1496 }
1497 if (count != 0) {
1498 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1499 }
1500
1501 if (mExternalStylusDataPending) {
1502 if (timeout) {
1503 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1504 clearStylusDataPendingFlags();
1505 mCurrentRawState.copyFrom(mLastRawState);
1506#if DEBUG_STYLUS_FUSION
1507 ALOGD("Timeout expired, synthesizing event with new stylus data");
1508#endif
1509 cookAndDispatch(when);
1510 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1511 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1512 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1513 }
1514 }
1515}
1516
1517void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1518 // Always start with a clean state.
1519 mCurrentCookedState.clear();
1520
1521 // Apply stylus buttons to current raw state.
1522 applyExternalStylusButtonState(when);
1523
1524 // Handle policy on initial down or hover events.
1525 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1526 mCurrentRawState.rawPointerData.pointerCount != 0;
1527
1528 uint32_t policyFlags = 0;
1529 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1530 if (initialDown || buttonsPressed) {
1531 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001532 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 getContext()->fadePointer();
1534 }
1535
1536 if (mParameters.wake) {
1537 policyFlags |= POLICY_FLAG_WAKE;
1538 }
1539 }
1540
1541 // Consume raw off-screen touches before cooking pointer data.
1542 // If touches are consumed, subsequent code will not receive any pointer data.
1543 if (consumeRawTouches(when, policyFlags)) {
1544 mCurrentRawState.rawPointerData.clear();
1545 }
1546
1547 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1548 // with cooked pointer data that has the same ids and indices as the raw data.
1549 // The following code can use either the raw or cooked data, as needed.
1550 cookPointerData();
1551
1552 // Apply stylus pressure to current cooked state.
1553 applyExternalStylusTouchState(when);
1554
1555 // Synthesize key down from raw buttons if needed.
1556 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1557 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1558 mCurrentCookedState.buttonState);
1559
1560 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001561 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1563 uint32_t id = idBits.clearFirstMarkedBit();
1564 const RawPointerData::Pointer& pointer =
1565 mCurrentRawState.rawPointerData.pointerForId(id);
1566 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1567 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1568 mCurrentCookedState.stylusIdBits.markBit(id);
1569 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1570 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1571 mCurrentCookedState.fingerIdBits.markBit(id);
1572 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1573 mCurrentCookedState.mouseIdBits.markBit(id);
1574 }
1575 }
1576 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1577 uint32_t id = idBits.clearFirstMarkedBit();
1578 const RawPointerData::Pointer& pointer =
1579 mCurrentRawState.rawPointerData.pointerForId(id);
1580 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1581 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1582 mCurrentCookedState.stylusIdBits.markBit(id);
1583 }
1584 }
1585
1586 // Stylus takes precedence over all tools, then mouse, then finger.
1587 PointerUsage pointerUsage = mPointerUsage;
1588 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1589 mCurrentCookedState.mouseIdBits.clear();
1590 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001591 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1593 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001594 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001595 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1596 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001597 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 }
1599
1600 dispatchPointerUsage(when, policyFlags, pointerUsage);
1601 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001602 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001604 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1605 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606
1607 mPointerController->setButtonState(mCurrentRawState.buttonState);
1608 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1609 mCurrentCookedState.cookedPointerData.idToIndex,
1610 mCurrentCookedState.cookedPointerData.touchingIdBits,
1611 mViewport.displayId);
1612 }
1613
1614 if (!mCurrentMotionAborted) {
1615 dispatchButtonRelease(when, policyFlags);
1616 dispatchHoverExit(when, policyFlags);
1617 dispatchTouches(when, policyFlags);
1618 dispatchHoverEnterAndMove(when, policyFlags);
1619 dispatchButtonPress(when, policyFlags);
1620 }
1621
1622 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1623 mCurrentMotionAborted = false;
1624 }
1625 }
1626
1627 // Synthesize key up from raw buttons if needed.
1628 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1629 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1630 mCurrentCookedState.buttonState);
1631
1632 // Clear some transient state.
1633 mCurrentRawState.rawVScroll = 0;
1634 mCurrentRawState.rawHScroll = 0;
1635
1636 // Copy current touch to last touch in preparation for the next cycle.
1637 mLastRawState.copyFrom(mCurrentRawState);
1638 mLastCookedState.copyFrom(mCurrentCookedState);
1639}
1640
1641void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001642 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1644 }
1645}
1646
1647void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1648 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1649 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1650
1651 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1652 float pressure = mExternalStylusState.pressure;
1653 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1654 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1655 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1656 }
1657 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1658 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1659
1660 PointerProperties& properties =
1661 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1662 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1663 properties.toolType = mExternalStylusState.toolType;
1664 }
1665 }
1666}
1667
1668bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001669 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001670 return false;
1671 }
1672
1673 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1674 state.rawPointerData.pointerCount != 0;
1675 if (initialDown) {
1676 if (mExternalStylusState.pressure != 0.0f) {
1677#if DEBUG_STYLUS_FUSION
1678 ALOGD("Have both stylus and touch data, beginning fusion");
1679#endif
1680 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1681 } else if (timeout) {
1682#if DEBUG_STYLUS_FUSION
1683 ALOGD("Timeout expired, assuming touch is not a stylus.");
1684#endif
1685 resetExternalStylus();
1686 } else {
1687 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1688 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1689 }
1690#if DEBUG_STYLUS_FUSION
1691 ALOGD("No stylus data but stylus is connected, requesting timeout "
1692 "(%" PRId64 "ms)",
1693 mExternalStylusFusionTimeout);
1694#endif
1695 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1696 return true;
1697 }
1698 }
1699
1700 // Check if the stylus pointer has gone up.
1701 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1702#if DEBUG_STYLUS_FUSION
1703 ALOGD("Stylus pointer is going up");
1704#endif
1705 mExternalStylusId = -1;
1706 }
1707
1708 return false;
1709}
1710
1711void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001712 if (mDeviceMode == DeviceMode::POINTER) {
1713 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1715 }
Michael Wright227c5542020-07-02 18:30:52 +01001716 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 if (mExternalStylusFusionTimeout < when) {
1718 processRawTouches(true /*timeout*/);
1719 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1720 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1721 }
1722 }
1723}
1724
1725void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1726 mExternalStylusState.copyFrom(state);
1727 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1728 // We're either in the middle of a fused stream of data or we're waiting on data before
1729 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1730 // data.
1731 mExternalStylusDataPending = true;
1732 processRawTouches(false /*timeout*/);
1733 }
1734}
1735
1736bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1737 // Check for release of a virtual key.
1738 if (mCurrentVirtualKey.down) {
1739 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1740 // Pointer went up while virtual key was down.
1741 mCurrentVirtualKey.down = false;
1742 if (!mCurrentVirtualKey.ignored) {
1743#if DEBUG_VIRTUAL_KEYS
1744 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1745 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1746#endif
1747 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1748 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1749 }
1750 return true;
1751 }
1752
1753 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1754 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1755 const RawPointerData::Pointer& pointer =
1756 mCurrentRawState.rawPointerData.pointerForId(id);
1757 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1758 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1759 // Pointer is still within the space of the virtual key.
1760 return true;
1761 }
1762 }
1763
1764 // Pointer left virtual key area or another pointer also went down.
1765 // Send key cancellation but do not consume the touch yet.
1766 // This is useful when the user swipes through from the virtual key area
1767 // into the main display surface.
1768 mCurrentVirtualKey.down = false;
1769 if (!mCurrentVirtualKey.ignored) {
1770#if DEBUG_VIRTUAL_KEYS
1771 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1772 mCurrentVirtualKey.scanCode);
1773#endif
1774 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1775 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1776 AKEY_EVENT_FLAG_CANCELED);
1777 }
1778 }
1779
1780 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1781 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1782 // Pointer just went down. Check for virtual key press or off-screen touches.
1783 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1784 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001785 // Exclude unscaled device for inside surface checking.
1786 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001787 // If exactly one pointer went down, check for virtual key hit.
1788 // Otherwise we will drop the entire stroke.
1789 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1790 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1791 if (virtualKey) {
1792 mCurrentVirtualKey.down = true;
1793 mCurrentVirtualKey.downTime = when;
1794 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1795 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1796 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001797 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1798 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001799
1800 if (!mCurrentVirtualKey.ignored) {
1801#if DEBUG_VIRTUAL_KEYS
1802 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1803 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1804#endif
1805 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1806 AKEY_EVENT_FLAG_FROM_SYSTEM |
1807 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1808 }
1809 }
1810 }
1811 return true;
1812 }
1813 }
1814
1815 // Disable all virtual key touches that happen within a short time interval of the
1816 // most recent touch within the screen area. The idea is to filter out stray
1817 // virtual key presses when interacting with the touch screen.
1818 //
1819 // Problems we're trying to solve:
1820 //
1821 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1822 // virtual key area that is implemented by a separate touch panel and accidentally
1823 // triggers a virtual key.
1824 //
1825 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1826 // area and accidentally triggers a virtual key. This often happens when virtual keys
1827 // are layed out below the screen near to where the on screen keyboard's space bar
1828 // is displayed.
1829 if (mConfig.virtualKeyQuietTime > 0 &&
1830 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001831 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 }
1833 return false;
1834}
1835
1836void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1837 int32_t keyEventAction, int32_t keyEventFlags) {
1838 int32_t keyCode = mCurrentVirtualKey.keyCode;
1839 int32_t scanCode = mCurrentVirtualKey.scanCode;
1840 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001841 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 policyFlags |= POLICY_FLAG_VIRTUAL;
1843
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001844 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1845 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1846 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001847 getListener()->notifyKey(&args);
1848}
1849
1850void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1851 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1852 if (!currentIdBits.isEmpty()) {
1853 int32_t metaState = getContext()->getGlobalMetaState();
1854 int32_t buttonState = mCurrentCookedState.buttonState;
1855 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1856 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1857 mCurrentCookedState.cookedPointerData.pointerProperties,
1858 mCurrentCookedState.cookedPointerData.pointerCoords,
1859 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1860 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1861 mCurrentMotionAborted = true;
1862 }
1863}
1864
1865void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1866 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1867 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1868 int32_t metaState = getContext()->getGlobalMetaState();
1869 int32_t buttonState = mCurrentCookedState.buttonState;
1870
1871 if (currentIdBits == lastIdBits) {
1872 if (!currentIdBits.isEmpty()) {
1873 // No pointer id changes so this is a move event.
1874 // The listener takes care of batching moves so we don't have to deal with that here.
1875 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1876 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1877 mCurrentCookedState.cookedPointerData.pointerProperties,
1878 mCurrentCookedState.cookedPointerData.pointerCoords,
1879 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1880 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1881 }
1882 } else {
1883 // There may be pointers going up and pointers going down and pointers moving
1884 // all at the same time.
1885 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1886 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1887 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1888 BitSet32 dispatchedIdBits(lastIdBits.value);
1889
1890 // Update last coordinates of pointers that have moved so that we observe the new
1891 // pointer positions at the same time as other pointers that have just gone up.
1892 bool moveNeeded =
1893 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1894 mCurrentCookedState.cookedPointerData.pointerCoords,
1895 mCurrentCookedState.cookedPointerData.idToIndex,
1896 mLastCookedState.cookedPointerData.pointerProperties,
1897 mLastCookedState.cookedPointerData.pointerCoords,
1898 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1899 if (buttonState != mLastCookedState.buttonState) {
1900 moveNeeded = true;
1901 }
1902
1903 // Dispatch pointer up events.
1904 while (!upIdBits.isEmpty()) {
1905 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001906 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1907 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1908 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909 mLastCookedState.cookedPointerData.pointerProperties,
1910 mLastCookedState.cookedPointerData.pointerCoords,
1911 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1913 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001914 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001915 }
1916
1917 // Dispatch move events if any of the remaining pointers moved from their old locations.
1918 // Although applications receive new locations as part of individual pointer up
1919 // events, they do not generally handle them except when presented in a move event.
1920 if (moveNeeded && !moveIdBits.isEmpty()) {
1921 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1922 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1923 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1924 mCurrentCookedState.cookedPointerData.pointerCoords,
1925 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1926 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1927 }
1928
1929 // Dispatch pointer down events using the new pointer locations.
1930 while (!downIdBits.isEmpty()) {
1931 uint32_t downId = downIdBits.clearFirstMarkedBit();
1932 dispatchedIdBits.markBit(downId);
1933
1934 if (dispatchedIdBits.count() == 1) {
1935 // First pointer is going down. Set down time.
1936 mDownTime = when;
1937 }
1938
1939 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1940 metaState, buttonState, 0,
1941 mCurrentCookedState.cookedPointerData.pointerProperties,
1942 mCurrentCookedState.cookedPointerData.pointerCoords,
1943 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1944 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1945 }
1946 }
1947}
1948
1949void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1950 if (mSentHoverEnter &&
1951 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1952 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1953 int32_t metaState = getContext()->getGlobalMetaState();
1954 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1955 mLastCookedState.buttonState, 0,
1956 mLastCookedState.cookedPointerData.pointerProperties,
1957 mLastCookedState.cookedPointerData.pointerCoords,
1958 mLastCookedState.cookedPointerData.idToIndex,
1959 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1960 mOrientedYPrecision, mDownTime);
1961 mSentHoverEnter = false;
1962 }
1963}
1964
1965void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1966 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1967 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1968 int32_t metaState = getContext()->getGlobalMetaState();
1969 if (!mSentHoverEnter) {
1970 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1971 metaState, mCurrentRawState.buttonState, 0,
1972 mCurrentCookedState.cookedPointerData.pointerProperties,
1973 mCurrentCookedState.cookedPointerData.pointerCoords,
1974 mCurrentCookedState.cookedPointerData.idToIndex,
1975 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1976 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1977 mSentHoverEnter = true;
1978 }
1979
1980 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
1981 mCurrentRawState.buttonState, 0,
1982 mCurrentCookedState.cookedPointerData.pointerProperties,
1983 mCurrentCookedState.cookedPointerData.pointerCoords,
1984 mCurrentCookedState.cookedPointerData.idToIndex,
1985 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
1986 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1987 }
1988}
1989
1990void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
1991 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
1992 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
1993 const int32_t metaState = getContext()->getGlobalMetaState();
1994 int32_t buttonState = mLastCookedState.buttonState;
1995 while (!releasedButtons.isEmpty()) {
1996 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
1997 buttonState &= ~actionButton;
1998 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1999 actionButton, 0, metaState, buttonState, 0,
2000 mCurrentCookedState.cookedPointerData.pointerProperties,
2001 mCurrentCookedState.cookedPointerData.pointerCoords,
2002 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2003 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2004 }
2005}
2006
2007void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2008 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2009 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2010 const int32_t metaState = getContext()->getGlobalMetaState();
2011 int32_t buttonState = mLastCookedState.buttonState;
2012 while (!pressedButtons.isEmpty()) {
2013 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2014 buttonState |= actionButton;
2015 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2016 0, metaState, buttonState, 0,
2017 mCurrentCookedState.cookedPointerData.pointerProperties,
2018 mCurrentCookedState.cookedPointerData.pointerCoords,
2019 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2020 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2021 }
2022}
2023
2024const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2025 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2026 return cookedPointerData.touchingIdBits;
2027 }
2028 return cookedPointerData.hoveringIdBits;
2029}
2030
2031void TouchInputMapper::cookPointerData() {
2032 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2033
2034 mCurrentCookedState.cookedPointerData.clear();
2035 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2036 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2037 mCurrentRawState.rawPointerData.hoveringIdBits;
2038 mCurrentCookedState.cookedPointerData.touchingIdBits =
2039 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002040 mCurrentCookedState.cookedPointerData.canceledIdBits =
2041 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002042
2043 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2044 mCurrentCookedState.buttonState = 0;
2045 } else {
2046 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2047 }
2048
2049 // Walk through the the active pointers and map device coordinates onto
2050 // surface coordinates and adjust for display orientation.
2051 for (uint32_t i = 0; i < currentPointerCount; i++) {
2052 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2053
2054 // Size
2055 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2056 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002057 case Calibration::SizeCalibration::GEOMETRIC:
2058 case Calibration::SizeCalibration::DIAMETER:
2059 case Calibration::SizeCalibration::BOX:
2060 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002061 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2062 touchMajor = in.touchMajor;
2063 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2064 toolMajor = in.toolMajor;
2065 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2066 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2067 : in.touchMajor;
2068 } else if (mRawPointerAxes.touchMajor.valid) {
2069 toolMajor = touchMajor = in.touchMajor;
2070 toolMinor = touchMinor =
2071 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2072 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2073 : in.touchMajor;
2074 } else if (mRawPointerAxes.toolMajor.valid) {
2075 touchMajor = toolMajor = in.toolMajor;
2076 touchMinor = toolMinor =
2077 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2078 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2079 : in.toolMajor;
2080 } else {
2081 ALOG_ASSERT(false,
2082 "No touch or tool axes. "
2083 "Size calibration should have been resolved to NONE.");
2084 touchMajor = 0;
2085 touchMinor = 0;
2086 toolMajor = 0;
2087 toolMinor = 0;
2088 size = 0;
2089 }
2090
2091 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2092 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2093 if (touchingCount > 1) {
2094 touchMajor /= touchingCount;
2095 touchMinor /= touchingCount;
2096 toolMajor /= touchingCount;
2097 toolMinor /= touchingCount;
2098 size /= touchingCount;
2099 }
2100 }
2101
Michael Wright227c5542020-07-02 18:30:52 +01002102 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103 touchMajor *= mGeometricScale;
2104 touchMinor *= mGeometricScale;
2105 toolMajor *= mGeometricScale;
2106 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002107 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2109 touchMinor = touchMajor;
2110 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2111 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002112 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113 touchMinor = touchMajor;
2114 toolMinor = toolMajor;
2115 }
2116
2117 mCalibration.applySizeScaleAndBias(&touchMajor);
2118 mCalibration.applySizeScaleAndBias(&touchMinor);
2119 mCalibration.applySizeScaleAndBias(&toolMajor);
2120 mCalibration.applySizeScaleAndBias(&toolMinor);
2121 size *= mSizeScale;
2122 break;
2123 default:
2124 touchMajor = 0;
2125 touchMinor = 0;
2126 toolMajor = 0;
2127 toolMinor = 0;
2128 size = 0;
2129 break;
2130 }
2131
2132 // Pressure
2133 float pressure;
2134 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002135 case Calibration::PressureCalibration::PHYSICAL:
2136 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002137 pressure = in.pressure * mPressureScale;
2138 break;
2139 default:
2140 pressure = in.isHovering ? 0 : 1;
2141 break;
2142 }
2143
2144 // Tilt and Orientation
2145 float tilt;
2146 float orientation;
2147 if (mHaveTilt) {
2148 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2149 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2150 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2151 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2152 } else {
2153 tilt = 0;
2154
2155 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002156 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 orientation = in.orientation * mOrientationScale;
2158 break;
Michael Wright227c5542020-07-02 18:30:52 +01002159 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002160 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2161 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2162 if (c1 != 0 || c2 != 0) {
2163 orientation = atan2f(c1, c2) * 0.5f;
2164 float confidence = hypotf(c1, c2);
2165 float scale = 1.0f + confidence / 16.0f;
2166 touchMajor *= scale;
2167 touchMinor /= scale;
2168 toolMajor *= scale;
2169 toolMinor /= scale;
2170 } else {
2171 orientation = 0;
2172 }
2173 break;
2174 }
2175 default:
2176 orientation = 0;
2177 }
2178 }
2179
2180 // Distance
2181 float distance;
2182 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002183 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 distance = in.distance * mDistanceScale;
2185 break;
2186 default:
2187 distance = 0;
2188 }
2189
2190 // Coverage
2191 int32_t rawLeft, rawTop, rawRight, rawBottom;
2192 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002193 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2195 rawRight = in.toolMinor & 0x0000ffff;
2196 rawBottom = in.toolMajor & 0x0000ffff;
2197 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2198 break;
2199 default:
2200 rawLeft = rawTop = rawRight = rawBottom = 0;
2201 break;
2202 }
2203
2204 // Adjust X,Y coords for device calibration
2205 // TODO: Adjust coverage coords?
2206 float xTransformed = in.x, yTransformed = in.y;
2207 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002208 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209
2210 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002211 float left, top, right, bottom;
2212
2213 switch (mSurfaceOrientation) {
2214 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002215 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2216 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2217 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2218 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2219 orientation -= M_PI_2;
2220 if (mOrientedRanges.haveOrientation &&
2221 orientation < mOrientedRanges.orientation.min) {
2222 orientation +=
2223 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2224 }
2225 break;
2226 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2228 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2229 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2230 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2231 orientation -= M_PI;
2232 if (mOrientedRanges.haveOrientation &&
2233 orientation < mOrientedRanges.orientation.min) {
2234 orientation +=
2235 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2236 }
2237 break;
2238 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2240 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2241 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2242 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2243 orientation += M_PI_2;
2244 if (mOrientedRanges.haveOrientation &&
2245 orientation > mOrientedRanges.orientation.max) {
2246 orientation -=
2247 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2248 }
2249 break;
2250 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2252 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2253 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2254 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2255 break;
2256 }
2257
2258 // Write output coords.
2259 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2260 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002261 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2262 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2264 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2265 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2266 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2267 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2268 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2269 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002270 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002271 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2272 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2273 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2274 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2275 } else {
2276 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2277 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2278 }
2279
Chris Ye364fdb52020-08-05 15:07:56 -07002280 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002281 uint32_t id = in.id;
2282 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2283 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2284 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2285 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2286 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2287 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2288 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2289 }
2290
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002291 // Write output properties.
2292 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 properties.clear();
2294 properties.id = id;
2295 properties.toolType = in.toolType;
2296
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002297 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002299 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002300 }
2301}
2302
2303void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2304 PointerUsage pointerUsage) {
2305 if (pointerUsage != mPointerUsage) {
2306 abortPointerUsage(when, policyFlags);
2307 mPointerUsage = pointerUsage;
2308 }
2309
2310 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002311 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2313 break;
Michael Wright227c5542020-07-02 18:30:52 +01002314 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 dispatchPointerStylus(when, policyFlags);
2316 break;
Michael Wright227c5542020-07-02 18:30:52 +01002317 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 dispatchPointerMouse(when, policyFlags);
2319 break;
Michael Wright227c5542020-07-02 18:30:52 +01002320 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 break;
2322 }
2323}
2324
2325void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2326 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002327 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 abortPointerGestures(when, policyFlags);
2329 break;
Michael Wright227c5542020-07-02 18:30:52 +01002330 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002331 abortPointerStylus(when, policyFlags);
2332 break;
Michael Wright227c5542020-07-02 18:30:52 +01002333 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 abortPointerMouse(when, policyFlags);
2335 break;
Michael Wright227c5542020-07-02 18:30:52 +01002336 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337 break;
2338 }
2339
Michael Wright227c5542020-07-02 18:30:52 +01002340 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341}
2342
2343void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2344 // Update current gesture coordinates.
2345 bool cancelPreviousGesture, finishPreviousGesture;
2346 bool sendEvents =
2347 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2348 if (!sendEvents) {
2349 return;
2350 }
2351 if (finishPreviousGesture) {
2352 cancelPreviousGesture = false;
2353 }
2354
2355 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002356 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002357 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 if (finishPreviousGesture || cancelPreviousGesture) {
2359 mPointerController->clearSpots();
2360 }
2361
Michael Wright227c5542020-07-02 18:30:52 +01002362 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002363 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2364 mPointerGesture.currentGestureIdToIndex,
2365 mPointerGesture.currentGestureIdBits,
2366 mPointerController->getDisplayId());
2367 }
2368 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002369 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 }
2371
2372 // Show or hide the pointer if needed.
2373 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002374 case PointerGesture::Mode::NEUTRAL:
2375 case PointerGesture::Mode::QUIET:
2376 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2377 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002379 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 }
2381 break;
Michael Wright227c5542020-07-02 18:30:52 +01002382 case PointerGesture::Mode::TAP:
2383 case PointerGesture::Mode::TAP_DRAG:
2384 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2385 case PointerGesture::Mode::HOVER:
2386 case PointerGesture::Mode::PRESS:
2387 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 // Unfade the pointer when the current gesture manipulates the
2389 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002390 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 break;
Michael Wright227c5542020-07-02 18:30:52 +01002392 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002393 // Fade the pointer when the current gesture manipulates a different
2394 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002395 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002396 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002398 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 }
2400 break;
2401 }
2402
2403 // Send events!
2404 int32_t metaState = getContext()->getGlobalMetaState();
2405 int32_t buttonState = mCurrentCookedState.buttonState;
2406
2407 // Update last coordinates of pointers that have moved so that we observe the new
2408 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002409 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2410 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2411 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2412 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2413 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2414 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 bool moveNeeded = false;
2416 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2417 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2418 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2419 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2420 mPointerGesture.lastGestureIdBits.value);
2421 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2422 mPointerGesture.currentGestureCoords,
2423 mPointerGesture.currentGestureIdToIndex,
2424 mPointerGesture.lastGestureProperties,
2425 mPointerGesture.lastGestureCoords,
2426 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2427 if (buttonState != mLastCookedState.buttonState) {
2428 moveNeeded = true;
2429 }
2430 }
2431
2432 // Send motion events for all pointers that went up or were canceled.
2433 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2434 if (!dispatchedGestureIdBits.isEmpty()) {
2435 if (cancelPreviousGesture) {
2436 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2437 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2438 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2439 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2440 mPointerGesture.downTime);
2441
2442 dispatchedGestureIdBits.clear();
2443 } else {
2444 BitSet32 upGestureIdBits;
2445 if (finishPreviousGesture) {
2446 upGestureIdBits = dispatchedGestureIdBits;
2447 } else {
2448 upGestureIdBits.value =
2449 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2450 }
2451 while (!upGestureIdBits.isEmpty()) {
2452 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2453
2454 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2455 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2456 mPointerGesture.lastGestureProperties,
2457 mPointerGesture.lastGestureCoords,
2458 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2459 0, mPointerGesture.downTime);
2460
2461 dispatchedGestureIdBits.clearBit(id);
2462 }
2463 }
2464 }
2465
2466 // Send motion events for all pointers that moved.
2467 if (moveNeeded) {
2468 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2469 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2470 mPointerGesture.currentGestureProperties,
2471 mPointerGesture.currentGestureCoords,
2472 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2473 mPointerGesture.downTime);
2474 }
2475
2476 // Send motion events for all pointers that went down.
2477 if (down) {
2478 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2479 ~dispatchedGestureIdBits.value);
2480 while (!downGestureIdBits.isEmpty()) {
2481 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2482 dispatchedGestureIdBits.markBit(id);
2483
2484 if (dispatchedGestureIdBits.count() == 1) {
2485 mPointerGesture.downTime = when;
2486 }
2487
2488 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2489 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2490 mPointerGesture.currentGestureCoords,
2491 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2492 0, mPointerGesture.downTime);
2493 }
2494 }
2495
2496 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002497 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2499 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2500 mPointerGesture.currentGestureProperties,
2501 mPointerGesture.currentGestureCoords,
2502 mPointerGesture.currentGestureIdToIndex,
2503 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2504 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2505 // Synthesize a hover move event after all pointers go up to indicate that
2506 // the pointer is hovering again even if the user is not currently touching
2507 // the touch pad. This ensures that a view will receive a fresh hover enter
2508 // event after a tap.
2509 float x, y;
2510 mPointerController->getPosition(&x, &y);
2511
2512 PointerProperties pointerProperties;
2513 pointerProperties.clear();
2514 pointerProperties.id = 0;
2515 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2516
2517 PointerCoords pointerCoords;
2518 pointerCoords.clear();
2519 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2520 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2521
2522 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002523 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2524 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2525 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2526 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2527 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 getListener()->notifyMotion(&args);
2529 }
2530
2531 // Update state.
2532 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2533 if (!down) {
2534 mPointerGesture.lastGestureIdBits.clear();
2535 } else {
2536 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2537 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2538 uint32_t id = idBits.clearFirstMarkedBit();
2539 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2540 mPointerGesture.lastGestureProperties[index].copyFrom(
2541 mPointerGesture.currentGestureProperties[index]);
2542 mPointerGesture.lastGestureCoords[index].copyFrom(
2543 mPointerGesture.currentGestureCoords[index]);
2544 mPointerGesture.lastGestureIdToIndex[id] = index;
2545 }
2546 }
2547}
2548
2549void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2550 // Cancel previously dispatches pointers.
2551 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2552 int32_t metaState = getContext()->getGlobalMetaState();
2553 int32_t buttonState = mCurrentRawState.buttonState;
2554 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2555 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2556 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2557 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2558 0, 0, mPointerGesture.downTime);
2559 }
2560
2561 // Reset the current pointer gesture.
2562 mPointerGesture.reset();
2563 mPointerVelocityControl.reset();
2564
2565 // Remove any current spots.
2566 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002567 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 mPointerController->clearSpots();
2569 }
2570}
2571
2572bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2573 bool* outFinishPreviousGesture, bool isTimeout) {
2574 *outCancelPreviousGesture = false;
2575 *outFinishPreviousGesture = false;
2576
2577 // Handle TAP timeout.
2578 if (isTimeout) {
2579#if DEBUG_GESTURES
2580 ALOGD("Gestures: Processing timeout");
2581#endif
2582
Michael Wright227c5542020-07-02 18:30:52 +01002583 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002584 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2585 // The tap/drag timeout has not yet expired.
2586 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2587 mConfig.pointerGestureTapDragInterval);
2588 } else {
2589 // The tap is finished.
2590#if DEBUG_GESTURES
2591 ALOGD("Gestures: TAP finished");
2592#endif
2593 *outFinishPreviousGesture = true;
2594
2595 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002596 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 mPointerGesture.currentGestureIdBits.clear();
2598
2599 mPointerVelocityControl.reset();
2600 return true;
2601 }
2602 }
2603
2604 // We did not handle this timeout.
2605 return false;
2606 }
2607
2608 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2609 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2610
2611 // Update the velocity tracker.
2612 {
2613 VelocityTracker::Position positions[MAX_POINTERS];
2614 uint32_t count = 0;
2615 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2616 uint32_t id = idBits.clearFirstMarkedBit();
2617 const RawPointerData::Pointer& pointer =
2618 mCurrentRawState.rawPointerData.pointerForId(id);
2619 positions[count].x = pointer.x * mPointerXMovementScale;
2620 positions[count].y = pointer.y * mPointerYMovementScale;
2621 }
2622 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2623 positions);
2624 }
2625
2626 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2627 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002628 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2629 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2630 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002631 mPointerGesture.resetTap();
2632 }
2633
2634 // Pick a new active touch id if needed.
2635 // Choose an arbitrary pointer that just went down, if there is one.
2636 // Otherwise choose an arbitrary remaining pointer.
2637 // This guarantees we always have an active touch id when there is at least one pointer.
2638 // We keep the same active touch id for as long as possible.
2639 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2640 int32_t activeTouchId = lastActiveTouchId;
2641 if (activeTouchId < 0) {
2642 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2643 activeTouchId = mPointerGesture.activeTouchId =
2644 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2645 mPointerGesture.firstTouchTime = when;
2646 }
2647 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2648 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2649 activeTouchId = mPointerGesture.activeTouchId =
2650 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2651 } else {
2652 activeTouchId = mPointerGesture.activeTouchId = -1;
2653 }
2654 }
2655
2656 // Determine whether we are in quiet time.
2657 bool isQuietTime = false;
2658 if (activeTouchId < 0) {
2659 mPointerGesture.resetQuietTime();
2660 } else {
2661 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2662 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002663 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2664 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2665 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666 currentFingerCount < 2) {
2667 // Enter quiet time when exiting swipe or freeform state.
2668 // This is to prevent accidentally entering the hover state and flinging the
2669 // pointer when finishing a swipe and there is still one pointer left onscreen.
2670 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002671 } else if (mPointerGesture.lastGestureMode ==
2672 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2674 // Enter quiet time when releasing the button and there are still two or more
2675 // fingers down. This may indicate that one finger was used to press the button
2676 // but it has not gone up yet.
2677 isQuietTime = true;
2678 }
2679 if (isQuietTime) {
2680 mPointerGesture.quietTime = when;
2681 }
2682 }
2683 }
2684
2685 // Switch states based on button and pointer state.
2686 if (isQuietTime) {
2687 // Case 1: Quiet time. (QUIET)
2688#if DEBUG_GESTURES
2689 ALOGD("Gestures: QUIET for next %0.3fms",
2690 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2691#endif
Michael Wright227c5542020-07-02 18:30:52 +01002692 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 *outFinishPreviousGesture = true;
2694 }
2695
2696 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002697 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698 mPointerGesture.currentGestureIdBits.clear();
2699
2700 mPointerVelocityControl.reset();
2701 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2702 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2703 // The pointer follows the active touch point.
2704 // Emit DOWN, MOVE, UP events at the pointer location.
2705 //
2706 // Only the active touch matters; other fingers are ignored. This policy helps
2707 // to handle the case where the user places a second finger on the touch pad
2708 // to apply the necessary force to depress an integrated button below the surface.
2709 // We don't want the second finger to be delivered to applications.
2710 //
2711 // For this to work well, we need to make sure to track the pointer that is really
2712 // active. If the user first puts one finger down to click then adds another
2713 // finger to drag then the active pointer should switch to the finger that is
2714 // being dragged.
2715#if DEBUG_GESTURES
2716 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2717 "currentFingerCount=%d",
2718 activeTouchId, currentFingerCount);
2719#endif
2720 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002721 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002722 *outFinishPreviousGesture = true;
2723 mPointerGesture.activeGestureId = 0;
2724 }
2725
2726 // Switch pointers if needed.
2727 // Find the fastest pointer and follow it.
2728 if (activeTouchId >= 0 && currentFingerCount > 1) {
2729 int32_t bestId = -1;
2730 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2731 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2732 uint32_t id = idBits.clearFirstMarkedBit();
2733 float vx, vy;
2734 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2735 float speed = hypotf(vx, vy);
2736 if (speed > bestSpeed) {
2737 bestId = id;
2738 bestSpeed = speed;
2739 }
2740 }
2741 }
2742 if (bestId >= 0 && bestId != activeTouchId) {
2743 mPointerGesture.activeTouchId = activeTouchId = bestId;
2744#if DEBUG_GESTURES
2745 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2746 "bestId=%d, bestSpeed=%0.3f",
2747 bestId, bestSpeed);
2748#endif
2749 }
2750 }
2751
2752 float deltaX = 0, deltaY = 0;
2753 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2754 const RawPointerData::Pointer& currentPointer =
2755 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2756 const RawPointerData::Pointer& lastPointer =
2757 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2758 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2759 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2760
2761 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2762 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2763
2764 // Move the pointer using a relative motion.
2765 // When using spots, the click will occur at the position of the anchor
2766 // spot and all other spots will move there.
2767 mPointerController->move(deltaX, deltaY);
2768 } else {
2769 mPointerVelocityControl.reset();
2770 }
2771
2772 float x, y;
2773 mPointerController->getPosition(&x, &y);
2774
Michael Wright227c5542020-07-02 18:30:52 +01002775 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002776 mPointerGesture.currentGestureIdBits.clear();
2777 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2778 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2779 mPointerGesture.currentGestureProperties[0].clear();
2780 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2781 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2782 mPointerGesture.currentGestureCoords[0].clear();
2783 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2784 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2785 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2786 } else if (currentFingerCount == 0) {
2787 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002788 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 *outFinishPreviousGesture = true;
2790 }
2791
2792 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2793 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2794 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002795 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2796 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 lastFingerCount == 1) {
2798 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2799 float x, y;
2800 mPointerController->getPosition(&x, &y);
2801 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2802 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2803#if DEBUG_GESTURES
2804 ALOGD("Gestures: TAP");
2805#endif
2806
2807 mPointerGesture.tapUpTime = when;
2808 getContext()->requestTimeoutAtTime(when +
2809 mConfig.pointerGestureTapDragInterval);
2810
2811 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002812 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 mPointerGesture.currentGestureIdBits.clear();
2814 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2815 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2816 mPointerGesture.currentGestureProperties[0].clear();
2817 mPointerGesture.currentGestureProperties[0].id =
2818 mPointerGesture.activeGestureId;
2819 mPointerGesture.currentGestureProperties[0].toolType =
2820 AMOTION_EVENT_TOOL_TYPE_FINGER;
2821 mPointerGesture.currentGestureCoords[0].clear();
2822 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2823 mPointerGesture.tapX);
2824 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2825 mPointerGesture.tapY);
2826 mPointerGesture.currentGestureCoords[0]
2827 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2828
2829 tapped = true;
2830 } else {
2831#if DEBUG_GESTURES
2832 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2833 y - mPointerGesture.tapY);
2834#endif
2835 }
2836 } else {
2837#if DEBUG_GESTURES
2838 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2839 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2840 (when - mPointerGesture.tapDownTime) * 0.000001f);
2841 } else {
2842 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2843 }
2844#endif
2845 }
2846 }
2847
2848 mPointerVelocityControl.reset();
2849
2850 if (!tapped) {
2851#if DEBUG_GESTURES
2852 ALOGD("Gestures: NEUTRAL");
2853#endif
2854 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002855 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 mPointerGesture.currentGestureIdBits.clear();
2857 }
2858 } else if (currentFingerCount == 1) {
2859 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2860 // The pointer follows the active touch point.
2861 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2862 // When in TAP_DRAG, emit MOVE events at the pointer location.
2863 ALOG_ASSERT(activeTouchId >= 0);
2864
Michael Wright227c5542020-07-02 18:30:52 +01002865 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2866 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2868 float x, y;
2869 mPointerController->getPosition(&x, &y);
2870 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2871 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002872 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 } else {
2874#if DEBUG_GESTURES
2875 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2876 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2877#endif
2878 }
2879 } else {
2880#if DEBUG_GESTURES
2881 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2882 (when - mPointerGesture.tapUpTime) * 0.000001f);
2883#endif
2884 }
Michael Wright227c5542020-07-02 18:30:52 +01002885 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2886 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 }
2888
2889 float deltaX = 0, deltaY = 0;
2890 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2891 const RawPointerData::Pointer& currentPointer =
2892 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2893 const RawPointerData::Pointer& lastPointer =
2894 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2895 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2896 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2897
2898 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2899 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2900
2901 // Move the pointer using a relative motion.
2902 // When using spots, the hover or drag will occur at the position of the anchor spot.
2903 mPointerController->move(deltaX, deltaY);
2904 } else {
2905 mPointerVelocityControl.reset();
2906 }
2907
2908 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002909 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910#if DEBUG_GESTURES
2911 ALOGD("Gestures: TAP_DRAG");
2912#endif
2913 down = true;
2914 } else {
2915#if DEBUG_GESTURES
2916 ALOGD("Gestures: HOVER");
2917#endif
Michael Wright227c5542020-07-02 18:30:52 +01002918 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 *outFinishPreviousGesture = true;
2920 }
2921 mPointerGesture.activeGestureId = 0;
2922 down = false;
2923 }
2924
2925 float x, y;
2926 mPointerController->getPosition(&x, &y);
2927
2928 mPointerGesture.currentGestureIdBits.clear();
2929 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2930 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2931 mPointerGesture.currentGestureProperties[0].clear();
2932 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2933 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2934 mPointerGesture.currentGestureCoords[0].clear();
2935 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2936 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2937 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2938 down ? 1.0f : 0.0f);
2939
2940 if (lastFingerCount == 0 && currentFingerCount != 0) {
2941 mPointerGesture.resetTap();
2942 mPointerGesture.tapDownTime = when;
2943 mPointerGesture.tapX = x;
2944 mPointerGesture.tapY = y;
2945 }
2946 } else {
2947 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2948 // We need to provide feedback for each finger that goes down so we cannot wait
2949 // for the fingers to move before deciding what to do.
2950 //
2951 // The ambiguous case is deciding what to do when there are two fingers down but they
2952 // have not moved enough to determine whether they are part of a drag or part of a
2953 // freeform gesture, or just a press or long-press at the pointer location.
2954 //
2955 // When there are two fingers we start with the PRESS hypothesis and we generate a
2956 // down at the pointer location.
2957 //
2958 // When the two fingers move enough or when additional fingers are added, we make
2959 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2960 ALOG_ASSERT(activeTouchId >= 0);
2961
2962 bool settled = when >=
2963 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01002964 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2965 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2966 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 *outFinishPreviousGesture = true;
2968 } else if (!settled && currentFingerCount > lastFingerCount) {
2969 // Additional pointers have gone down but not yet settled.
2970 // Reset the gesture.
2971#if DEBUG_GESTURES
2972 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2973 "settle time remaining %0.3fms",
2974 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2975 when) * 0.000001f);
2976#endif
2977 *outCancelPreviousGesture = true;
2978 } else {
2979 // Continue previous gesture.
2980 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
2981 }
2982
2983 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01002984 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985 mPointerGesture.activeGestureId = 0;
2986 mPointerGesture.referenceIdBits.clear();
2987 mPointerVelocityControl.reset();
2988
2989 // Use the centroid and pointer location as the reference points for the gesture.
2990#if DEBUG_GESTURES
2991 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
2992 "settle time remaining %0.3fms",
2993 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2994 when) * 0.000001f);
2995#endif
2996 mCurrentRawState.rawPointerData
2997 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
2998 &mPointerGesture.referenceTouchY);
2999 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3000 &mPointerGesture.referenceGestureY);
3001 }
3002
3003 // Clear the reference deltas for fingers not yet included in the reference calculation.
3004 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3005 ~mPointerGesture.referenceIdBits.value);
3006 !idBits.isEmpty();) {
3007 uint32_t id = idBits.clearFirstMarkedBit();
3008 mPointerGesture.referenceDeltas[id].dx = 0;
3009 mPointerGesture.referenceDeltas[id].dy = 0;
3010 }
3011 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3012
3013 // Add delta for all fingers and calculate a common movement delta.
3014 float commonDeltaX = 0, commonDeltaY = 0;
3015 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3016 mCurrentCookedState.fingerIdBits.value);
3017 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3018 bool first = (idBits == commonIdBits);
3019 uint32_t id = idBits.clearFirstMarkedBit();
3020 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3021 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3022 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3023 delta.dx += cpd.x - lpd.x;
3024 delta.dy += cpd.y - lpd.y;
3025
3026 if (first) {
3027 commonDeltaX = delta.dx;
3028 commonDeltaY = delta.dy;
3029 } else {
3030 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3031 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3032 }
3033 }
3034
3035 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003036 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003037 float dist[MAX_POINTER_ID + 1];
3038 int32_t distOverThreshold = 0;
3039 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3040 uint32_t id = idBits.clearFirstMarkedBit();
3041 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3042 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3043 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3044 distOverThreshold += 1;
3045 }
3046 }
3047
3048 // Only transition when at least two pointers have moved further than
3049 // the minimum distance threshold.
3050 if (distOverThreshold >= 2) {
3051 if (currentFingerCount > 2) {
3052 // There are more than two pointers, switch to FREEFORM.
3053#if DEBUG_GESTURES
3054 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3055 currentFingerCount);
3056#endif
3057 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003058 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 } else {
3060 // There are exactly two pointers.
3061 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3062 uint32_t id1 = idBits.clearFirstMarkedBit();
3063 uint32_t id2 = idBits.firstMarkedBit();
3064 const RawPointerData::Pointer& p1 =
3065 mCurrentRawState.rawPointerData.pointerForId(id1);
3066 const RawPointerData::Pointer& p2 =
3067 mCurrentRawState.rawPointerData.pointerForId(id2);
3068 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3069 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3070 // There are two pointers but they are too far apart for a SWIPE,
3071 // switch to FREEFORM.
3072#if DEBUG_GESTURES
3073 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3074 mutualDistance, mPointerGestureMaxSwipeWidth);
3075#endif
3076 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003077 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003078 } else {
3079 // There are two pointers. Wait for both pointers to start moving
3080 // before deciding whether this is a SWIPE or FREEFORM gesture.
3081 float dist1 = dist[id1];
3082 float dist2 = dist[id2];
3083 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3084 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3085 // Calculate the dot product of the displacement vectors.
3086 // When the vectors are oriented in approximately the same direction,
3087 // the angle betweeen them is near zero and the cosine of the angle
3088 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3089 // mag(v2).
3090 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3091 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3092 float dx1 = delta1.dx * mPointerXZoomScale;
3093 float dy1 = delta1.dy * mPointerYZoomScale;
3094 float dx2 = delta2.dx * mPointerXZoomScale;
3095 float dy2 = delta2.dy * mPointerYZoomScale;
3096 float dot = dx1 * dx2 + dy1 * dy2;
3097 float cosine = dot / (dist1 * dist2); // denominator always > 0
3098 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3099 // Pointers are moving in the same direction. Switch to SWIPE.
3100#if DEBUG_GESTURES
3101 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3102 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3103 "cosine %0.3f >= %0.3f",
3104 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3105 mConfig.pointerGestureMultitouchMinDistance, cosine,
3106 mConfig.pointerGestureSwipeTransitionAngleCosine);
3107#endif
Michael Wright227c5542020-07-02 18:30:52 +01003108 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003109 } else {
3110 // Pointers are moving in different directions. Switch to FREEFORM.
3111#if DEBUG_GESTURES
3112 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3113 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3114 "cosine %0.3f < %0.3f",
3115 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3116 mConfig.pointerGestureMultitouchMinDistance, cosine,
3117 mConfig.pointerGestureSwipeTransitionAngleCosine);
3118#endif
3119 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003120 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003121 }
3122 }
3123 }
3124 }
3125 }
Michael Wright227c5542020-07-02 18:30:52 +01003126 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003127 // Switch from SWIPE to FREEFORM if additional pointers go down.
3128 // Cancel previous gesture.
3129 if (currentFingerCount > 2) {
3130#if DEBUG_GESTURES
3131 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3132 currentFingerCount);
3133#endif
3134 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003135 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003136 }
3137 }
3138
3139 // Move the reference points based on the overall group motion of the fingers
3140 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003141 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003142 (commonDeltaX || commonDeltaY)) {
3143 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3144 uint32_t id = idBits.clearFirstMarkedBit();
3145 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3146 delta.dx = 0;
3147 delta.dy = 0;
3148 }
3149
3150 mPointerGesture.referenceTouchX += commonDeltaX;
3151 mPointerGesture.referenceTouchY += commonDeltaY;
3152
3153 commonDeltaX *= mPointerXMovementScale;
3154 commonDeltaY *= mPointerYMovementScale;
3155
3156 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3157 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3158
3159 mPointerGesture.referenceGestureX += commonDeltaX;
3160 mPointerGesture.referenceGestureY += commonDeltaY;
3161 }
3162
3163 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003164 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3165 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003166 // PRESS or SWIPE mode.
3167#if DEBUG_GESTURES
3168 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3169 "activeGestureId=%d, currentTouchPointerCount=%d",
3170 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3171#endif
3172 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3173
3174 mPointerGesture.currentGestureIdBits.clear();
3175 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3176 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3177 mPointerGesture.currentGestureProperties[0].clear();
3178 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3179 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3180 mPointerGesture.currentGestureCoords[0].clear();
3181 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3182 mPointerGesture.referenceGestureX);
3183 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3184 mPointerGesture.referenceGestureY);
3185 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003186 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003187 // FREEFORM mode.
3188#if DEBUG_GESTURES
3189 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3190 "activeGestureId=%d, currentTouchPointerCount=%d",
3191 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3192#endif
3193 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3194
3195 mPointerGesture.currentGestureIdBits.clear();
3196
3197 BitSet32 mappedTouchIdBits;
3198 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003199 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003200 // Initially, assign the active gesture id to the active touch point
3201 // if there is one. No other touch id bits are mapped yet.
3202 if (!*outCancelPreviousGesture) {
3203 mappedTouchIdBits.markBit(activeTouchId);
3204 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3205 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3206 mPointerGesture.activeGestureId;
3207 } else {
3208 mPointerGesture.activeGestureId = -1;
3209 }
3210 } else {
3211 // Otherwise, assume we mapped all touches from the previous frame.
3212 // Reuse all mappings that are still applicable.
3213 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3214 mCurrentCookedState.fingerIdBits.value;
3215 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3216
3217 // Check whether we need to choose a new active gesture id because the
3218 // current went went up.
3219 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3220 ~mCurrentCookedState.fingerIdBits.value);
3221 !upTouchIdBits.isEmpty();) {
3222 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3223 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3224 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3225 mPointerGesture.activeGestureId = -1;
3226 break;
3227 }
3228 }
3229 }
3230
3231#if DEBUG_GESTURES
3232 ALOGD("Gestures: FREEFORM follow up "
3233 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3234 "activeGestureId=%d",
3235 mappedTouchIdBits.value, usedGestureIdBits.value,
3236 mPointerGesture.activeGestureId);
3237#endif
3238
3239 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3240 for (uint32_t i = 0; i < currentFingerCount; i++) {
3241 uint32_t touchId = idBits.clearFirstMarkedBit();
3242 uint32_t gestureId;
3243 if (!mappedTouchIdBits.hasBit(touchId)) {
3244 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3245 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3246#if DEBUG_GESTURES
3247 ALOGD("Gestures: FREEFORM "
3248 "new mapping for touch id %d -> gesture id %d",
3249 touchId, gestureId);
3250#endif
3251 } else {
3252 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3253#if DEBUG_GESTURES
3254 ALOGD("Gestures: FREEFORM "
3255 "existing mapping for touch id %d -> gesture id %d",
3256 touchId, gestureId);
3257#endif
3258 }
3259 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3260 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3261
3262 const RawPointerData::Pointer& pointer =
3263 mCurrentRawState.rawPointerData.pointerForId(touchId);
3264 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3265 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3266 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3267
3268 mPointerGesture.currentGestureProperties[i].clear();
3269 mPointerGesture.currentGestureProperties[i].id = gestureId;
3270 mPointerGesture.currentGestureProperties[i].toolType =
3271 AMOTION_EVENT_TOOL_TYPE_FINGER;
3272 mPointerGesture.currentGestureCoords[i].clear();
3273 mPointerGesture.currentGestureCoords[i]
3274 .setAxisValue(AMOTION_EVENT_AXIS_X,
3275 mPointerGesture.referenceGestureX + deltaX);
3276 mPointerGesture.currentGestureCoords[i]
3277 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3278 mPointerGesture.referenceGestureY + deltaY);
3279 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3280 1.0f);
3281 }
3282
3283 if (mPointerGesture.activeGestureId < 0) {
3284 mPointerGesture.activeGestureId =
3285 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3286#if DEBUG_GESTURES
3287 ALOGD("Gestures: FREEFORM new "
3288 "activeGestureId=%d",
3289 mPointerGesture.activeGestureId);
3290#endif
3291 }
3292 }
3293 }
3294
3295 mPointerController->setButtonState(mCurrentRawState.buttonState);
3296
3297#if DEBUG_GESTURES
3298 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3299 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3300 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3301 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3302 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3303 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3304 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3305 uint32_t id = idBits.clearFirstMarkedBit();
3306 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3307 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3308 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3309 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3310 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3311 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3312 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3313 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3314 }
3315 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3316 uint32_t id = idBits.clearFirstMarkedBit();
3317 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3318 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3319 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3320 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3321 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3322 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3323 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3324 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3325 }
3326#endif
3327 return true;
3328}
3329
3330void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3331 mPointerSimple.currentCoords.clear();
3332 mPointerSimple.currentProperties.clear();
3333
3334 bool down, hovering;
3335 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3336 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3337 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3338 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3339 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3340 mPointerController->setPosition(x, y);
3341
3342 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3343 down = !hovering;
3344
3345 mPointerController->getPosition(&x, &y);
3346 mPointerSimple.currentCoords.copyFrom(
3347 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3348 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3349 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3350 mPointerSimple.currentProperties.id = 0;
3351 mPointerSimple.currentProperties.toolType =
3352 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3353 } else {
3354 down = false;
3355 hovering = false;
3356 }
3357
3358 dispatchPointerSimple(when, policyFlags, down, hovering);
3359}
3360
3361void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3362 abortPointerSimple(when, policyFlags);
3363}
3364
3365void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3366 mPointerSimple.currentCoords.clear();
3367 mPointerSimple.currentProperties.clear();
3368
3369 bool down, hovering;
3370 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3371 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3372 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3373 float deltaX = 0, deltaY = 0;
3374 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3375 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3376 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3377 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3378 mPointerXMovementScale;
3379 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3380 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3381 mPointerYMovementScale;
3382
3383 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3384 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3385
3386 mPointerController->move(deltaX, deltaY);
3387 } else {
3388 mPointerVelocityControl.reset();
3389 }
3390
3391 down = isPointerDown(mCurrentRawState.buttonState);
3392 hovering = !down;
3393
3394 float x, y;
3395 mPointerController->getPosition(&x, &y);
3396 mPointerSimple.currentCoords.copyFrom(
3397 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3398 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3399 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3400 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3401 hovering ? 0.0f : 1.0f);
3402 mPointerSimple.currentProperties.id = 0;
3403 mPointerSimple.currentProperties.toolType =
3404 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3405 } else {
3406 mPointerVelocityControl.reset();
3407
3408 down = false;
3409 hovering = false;
3410 }
3411
3412 dispatchPointerSimple(when, policyFlags, down, hovering);
3413}
3414
3415void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3416 abortPointerSimple(when, policyFlags);
3417
3418 mPointerVelocityControl.reset();
3419}
3420
3421void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3422 bool hovering) {
3423 int32_t metaState = getContext()->getGlobalMetaState();
3424 int32_t displayId = mViewport.displayId;
3425
3426 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003427 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 mPointerController->clearSpots();
3429 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003430 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003431 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003432 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003433 }
3434 displayId = mPointerController->getDisplayId();
3435
3436 float xCursorPosition;
3437 float yCursorPosition;
3438 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3439
3440 if (mPointerSimple.down && !down) {
3441 mPointerSimple.down = false;
3442
3443 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003444 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3445 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 mLastRawState.buttonState, MotionClassification::NONE,
3447 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3448 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3449 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3450 /* videoFrames */ {});
3451 getListener()->notifyMotion(&args);
3452 }
3453
3454 if (mPointerSimple.hovering && !hovering) {
3455 mPointerSimple.hovering = false;
3456
3457 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003458 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3459 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3460 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003461 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3462 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3463 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3464 /* videoFrames */ {});
3465 getListener()->notifyMotion(&args);
3466 }
3467
3468 if (down) {
3469 if (!mPointerSimple.down) {
3470 mPointerSimple.down = true;
3471 mPointerSimple.downTime = when;
3472
3473 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003474 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003475 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3476 metaState, mCurrentRawState.buttonState,
3477 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3478 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3479 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3480 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3481 getListener()->notifyMotion(&args);
3482 }
3483
3484 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003485 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3486 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 mCurrentRawState.buttonState, MotionClassification::NONE,
3488 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3489 &mPointerSimple.currentCoords, mOrientedXPrecision,
3490 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3491 mPointerSimple.downTime, /* videoFrames */ {});
3492 getListener()->notifyMotion(&args);
3493 }
3494
3495 if (hovering) {
3496 if (!mPointerSimple.hovering) {
3497 mPointerSimple.hovering = true;
3498
3499 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003500 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3502 metaState, mCurrentRawState.buttonState,
3503 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3504 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3505 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3506 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3507 getListener()->notifyMotion(&args);
3508 }
3509
3510 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003511 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3512 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3513 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3515 &mPointerSimple.currentCoords, mOrientedXPrecision,
3516 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3517 mPointerSimple.downTime, /* videoFrames */ {});
3518 getListener()->notifyMotion(&args);
3519 }
3520
3521 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3522 float vscroll = mCurrentRawState.rawVScroll;
3523 float hscroll = mCurrentRawState.rawHScroll;
3524 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3525 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3526
3527 // Send scroll.
3528 PointerCoords pointerCoords;
3529 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3530 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3531 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3532
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003533 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3534 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 mCurrentRawState.buttonState, MotionClassification::NONE,
3536 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3537 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3538 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3539 /* videoFrames */ {});
3540 getListener()->notifyMotion(&args);
3541 }
3542
3543 // Save state.
3544 if (down || hovering) {
3545 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3546 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3547 } else {
3548 mPointerSimple.reset();
3549 }
3550}
3551
3552void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3553 mPointerSimple.currentCoords.clear();
3554 mPointerSimple.currentProperties.clear();
3555
3556 dispatchPointerSimple(when, policyFlags, false, false);
3557}
3558
3559void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3560 int32_t action, int32_t actionButton, int32_t flags,
3561 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3562 const PointerProperties* properties,
3563 const PointerCoords* coords, const uint32_t* idToIndex,
3564 BitSet32 idBits, int32_t changedId, float xPrecision,
3565 float yPrecision, nsecs_t downTime) {
3566 PointerCoords pointerCoords[MAX_POINTERS];
3567 PointerProperties pointerProperties[MAX_POINTERS];
3568 uint32_t pointerCount = 0;
3569 while (!idBits.isEmpty()) {
3570 uint32_t id = idBits.clearFirstMarkedBit();
3571 uint32_t index = idToIndex[id];
3572 pointerProperties[pointerCount].copyFrom(properties[index]);
3573 pointerCoords[pointerCount].copyFrom(coords[index]);
3574
3575 if (changedId >= 0 && id == uint32_t(changedId)) {
3576 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3577 }
3578
3579 pointerCount += 1;
3580 }
3581
3582 ALOG_ASSERT(pointerCount != 0);
3583
3584 if (changedId >= 0 && pointerCount == 1) {
3585 // Replace initial down and final up action.
3586 // We can compare the action without masking off the changed pointer index
3587 // because we know the index is 0.
3588 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3589 action = AMOTION_EVENT_ACTION_DOWN;
3590 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003591 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3592 action = AMOTION_EVENT_ACTION_CANCEL;
3593 } else {
3594 action = AMOTION_EVENT_ACTION_UP;
3595 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 } else {
3597 // Can't happen.
3598 ALOG_ASSERT(false);
3599 }
3600 }
3601 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3602 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003603 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3605 }
3606 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3607 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003608 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 std::for_each(frames.begin(), frames.end(),
3610 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003611 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3612 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3614 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3615 downTime, std::move(frames));
3616 getListener()->notifyMotion(&args);
3617}
3618
3619bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3620 const PointerCoords* inCoords,
3621 const uint32_t* inIdToIndex,
3622 PointerProperties* outProperties,
3623 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3624 BitSet32 idBits) const {
3625 bool changed = false;
3626 while (!idBits.isEmpty()) {
3627 uint32_t id = idBits.clearFirstMarkedBit();
3628 uint32_t inIndex = inIdToIndex[id];
3629 uint32_t outIndex = outIdToIndex[id];
3630
3631 const PointerProperties& curInProperties = inProperties[inIndex];
3632 const PointerCoords& curInCoords = inCoords[inIndex];
3633 PointerProperties& curOutProperties = outProperties[outIndex];
3634 PointerCoords& curOutCoords = outCoords[outIndex];
3635
3636 if (curInProperties != curOutProperties) {
3637 curOutProperties.copyFrom(curInProperties);
3638 changed = true;
3639 }
3640
3641 if (curInCoords != curOutCoords) {
3642 curOutCoords.copyFrom(curInCoords);
3643 changed = true;
3644 }
3645 }
3646 return changed;
3647}
3648
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649void TouchInputMapper::cancelTouch(nsecs_t when) {
3650 abortPointerUsage(when, 0 /*policyFlags*/);
3651 abortTouches(when, 0 /* policyFlags*/);
3652}
3653
Arthur Hung4197f6b2020-03-16 15:39:59 +08003654// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003655void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003656 // Scale to surface coordinate.
3657 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3658 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3659
3660 // Rotate to surface coordinate.
3661 // 0 - no swap and reverse.
3662 // 90 - swap x/y and reverse y.
3663 // 180 - reverse x, y.
3664 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003665 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003666 case DISPLAY_ORIENTATION_0:
3667 x = xScaled + mXTranslate;
3668 y = yScaled + mYTranslate;
3669 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003670 case DISPLAY_ORIENTATION_90:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003671 y = mSurfaceRight - xScaled;
3672 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003673 break;
3674 case DISPLAY_ORIENTATION_180:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003675 x = mSurfaceRight - xScaled;
3676 y = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003677 break;
3678 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003679 y = xScaled + mXTranslate;
3680 x = mSurfaceBottom - yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003681 break;
3682 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003683 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003684 }
3685}
3686
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003687bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003688 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3689 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3690
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003691 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003692 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003693 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003694 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695}
3696
3697const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3698 for (const VirtualKey& virtualKey : mVirtualKeys) {
3699#if DEBUG_VIRTUAL_KEYS
3700 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3701 "left=%d, top=%d, right=%d, bottom=%d",
3702 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3703 virtualKey.hitRight, virtualKey.hitBottom);
3704#endif
3705
3706 if (virtualKey.isHit(x, y)) {
3707 return &virtualKey;
3708 }
3709 }
3710
3711 return nullptr;
3712}
3713
3714void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3715 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3716 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3717
3718 current->rawPointerData.clearIdBits();
3719
3720 if (currentPointerCount == 0) {
3721 // No pointers to assign.
3722 return;
3723 }
3724
3725 if (lastPointerCount == 0) {
3726 // All pointers are new.
3727 for (uint32_t i = 0; i < currentPointerCount; i++) {
3728 uint32_t id = i;
3729 current->rawPointerData.pointers[i].id = id;
3730 current->rawPointerData.idToIndex[id] = i;
3731 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3732 }
3733 return;
3734 }
3735
3736 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3737 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3738 // Only one pointer and no change in count so it must have the same id as before.
3739 uint32_t id = last->rawPointerData.pointers[0].id;
3740 current->rawPointerData.pointers[0].id = id;
3741 current->rawPointerData.idToIndex[id] = 0;
3742 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3743 return;
3744 }
3745
3746 // General case.
3747 // We build a heap of squared euclidean distances between current and last pointers
3748 // associated with the current and last pointer indices. Then, we find the best
3749 // match (by distance) for each current pointer.
3750 // The pointers must have the same tool type but it is possible for them to
3751 // transition from hovering to touching or vice-versa while retaining the same id.
3752 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3753
3754 uint32_t heapSize = 0;
3755 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3756 currentPointerIndex++) {
3757 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3758 lastPointerIndex++) {
3759 const RawPointerData::Pointer& currentPointer =
3760 current->rawPointerData.pointers[currentPointerIndex];
3761 const RawPointerData::Pointer& lastPointer =
3762 last->rawPointerData.pointers[lastPointerIndex];
3763 if (currentPointer.toolType == lastPointer.toolType) {
3764 int64_t deltaX = currentPointer.x - lastPointer.x;
3765 int64_t deltaY = currentPointer.y - lastPointer.y;
3766
3767 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3768
3769 // Insert new element into the heap (sift up).
3770 heap[heapSize].currentPointerIndex = currentPointerIndex;
3771 heap[heapSize].lastPointerIndex = lastPointerIndex;
3772 heap[heapSize].distance = distance;
3773 heapSize += 1;
3774 }
3775 }
3776 }
3777
3778 // Heapify
3779 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3780 startIndex -= 1;
3781 for (uint32_t parentIndex = startIndex;;) {
3782 uint32_t childIndex = parentIndex * 2 + 1;
3783 if (childIndex >= heapSize) {
3784 break;
3785 }
3786
3787 if (childIndex + 1 < heapSize &&
3788 heap[childIndex + 1].distance < heap[childIndex].distance) {
3789 childIndex += 1;
3790 }
3791
3792 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3793 break;
3794 }
3795
3796 swap(heap[parentIndex], heap[childIndex]);
3797 parentIndex = childIndex;
3798 }
3799 }
3800
3801#if DEBUG_POINTER_ASSIGNMENT
3802 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3803 for (size_t i = 0; i < heapSize; i++) {
3804 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3805 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3806 }
3807#endif
3808
3809 // Pull matches out by increasing order of distance.
3810 // To avoid reassigning pointers that have already been matched, the loop keeps track
3811 // of which last and current pointers have been matched using the matchedXXXBits variables.
3812 // It also tracks the used pointer id bits.
3813 BitSet32 matchedLastBits(0);
3814 BitSet32 matchedCurrentBits(0);
3815 BitSet32 usedIdBits(0);
3816 bool first = true;
3817 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3818 while (heapSize > 0) {
3819 if (first) {
3820 // The first time through the loop, we just consume the root element of
3821 // the heap (the one with smallest distance).
3822 first = false;
3823 } else {
3824 // Previous iterations consumed the root element of the heap.
3825 // Pop root element off of the heap (sift down).
3826 heap[0] = heap[heapSize];
3827 for (uint32_t parentIndex = 0;;) {
3828 uint32_t childIndex = parentIndex * 2 + 1;
3829 if (childIndex >= heapSize) {
3830 break;
3831 }
3832
3833 if (childIndex + 1 < heapSize &&
3834 heap[childIndex + 1].distance < heap[childIndex].distance) {
3835 childIndex += 1;
3836 }
3837
3838 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3839 break;
3840 }
3841
3842 swap(heap[parentIndex], heap[childIndex]);
3843 parentIndex = childIndex;
3844 }
3845
3846#if DEBUG_POINTER_ASSIGNMENT
3847 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003848 for (size_t j = 0; j < heapSize; j++) {
3849 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3850 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003851 }
3852#endif
3853 }
3854
3855 heapSize -= 1;
3856
3857 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3858 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3859
3860 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3861 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3862
3863 matchedCurrentBits.markBit(currentPointerIndex);
3864 matchedLastBits.markBit(lastPointerIndex);
3865
3866 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3867 current->rawPointerData.pointers[currentPointerIndex].id = id;
3868 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3869 current->rawPointerData.markIdBit(id,
3870 current->rawPointerData.isHovering(
3871 currentPointerIndex));
3872 usedIdBits.markBit(id);
3873
3874#if DEBUG_POINTER_ASSIGNMENT
3875 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3876 ", distance=%" PRIu64,
3877 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3878#endif
3879 break;
3880 }
3881 }
3882
3883 // Assign fresh ids to pointers that were not matched in the process.
3884 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3885 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3886 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3887
3888 current->rawPointerData.pointers[currentPointerIndex].id = id;
3889 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3890 current->rawPointerData.markIdBit(id,
3891 current->rawPointerData.isHovering(currentPointerIndex));
3892
3893#if DEBUG_POINTER_ASSIGNMENT
3894 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3895#endif
3896 }
3897}
3898
3899int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3900 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3901 return AKEY_STATE_VIRTUAL;
3902 }
3903
3904 for (const VirtualKey& virtualKey : mVirtualKeys) {
3905 if (virtualKey.keyCode == keyCode) {
3906 return AKEY_STATE_UP;
3907 }
3908 }
3909
3910 return AKEY_STATE_UNKNOWN;
3911}
3912
3913int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3914 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3915 return AKEY_STATE_VIRTUAL;
3916 }
3917
3918 for (const VirtualKey& virtualKey : mVirtualKeys) {
3919 if (virtualKey.scanCode == scanCode) {
3920 return AKEY_STATE_UP;
3921 }
3922 }
3923
3924 return AKEY_STATE_UNKNOWN;
3925}
3926
3927bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3928 const int32_t* keyCodes, uint8_t* outFlags) {
3929 for (const VirtualKey& virtualKey : mVirtualKeys) {
3930 for (size_t i = 0; i < numCodes; i++) {
3931 if (virtualKey.keyCode == keyCodes[i]) {
3932 outFlags[i] = 1;
3933 }
3934 }
3935 }
3936
3937 return true;
3938}
3939
3940std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3941 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003942 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943 return std::make_optional(mPointerController->getDisplayId());
3944 } else {
3945 return std::make_optional(mViewport.displayId);
3946 }
3947 }
3948 return std::nullopt;
3949}
3950
3951} // namespace android